Nothing Special   »   [go: up one dir, main page]

Javascript Day-4

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 9

Day:4......................

.................................................
JSON.stringify:

1) JSON.stringify is a method that converts a JavaScript object or value to a JSON


string.
2) It takes a JavaScript object or value as input and returns a JSON string
representation of that object.
3) This method is commonly used when you want to send data to a server or store it
in a file as a JSON string.

ex:

const obj = { name: "John", age: 30 };


const jsonString = JSON.stringify(obj);
console.log(jsonString);
..................................................
JSON.parse:

1) JSON.parse is a method that converts a JSON string to a JavaScript object.


2) It takes a JSON string as input and returns a JavaScript object corresponding to
that JSON string.
3) This method is useful when you receive JSON data from a server or read JSON data
from a file, and you want to parse that data into a usable JavaScript object.

ex:

const jsonString = '{"name":"John","age":30}';


const obj = JSON.parse(jsonString);
console.log(obj);

.......................................................
Post Data:

html:

<input type="text" id="titleInput" placeholder="Enter title">


<input type="text" id="userIdInput" placeholder="Enter userId">
<button >

js:

function submitPost() {
var title = document.getElementById('titleInput').value;
var userId = document.getElementById('userIdInput').value;

// Create the POST request with the dynamic values


fetch('https://dummyjson.com/posts/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: title,
userId: userId,
/* other post data */
})
})
.then(res => res.json())
.then(console.log);
}

................................................

DOM:

The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of an HTML or XML document as a tree-like structure, where
each node represents an element, attribute, or piece of text in the document.

console.log(window);
console.log(this);
console.log(window.location);

....................................
console.log(window.document);
(or)
console.log(document);
................................................

how many ways to select dom element in javascript:

html:

<h1 id="title">Hello, World!</h1>


<p class="myClass">Paragraph 1</p>
<p class="myClass">Paragraph 2</p>
<div>
<span>Span 1</span>
<span>Span 2</span>
</div>

1) getElementById:

This method selects an element based on its unique id attribute.

const element = document.getElementById('myDiv');

2) getElementsByClassName:

This method selects elements based on their shared class name.


const elements = document.getElementsByClassName('myClass');

3) getElementsByTagName:
This method selects elements based on their HTML tag name.
const elements = document.getElementsByTagName('h1');

4) querySelector:

This method selects the first element that matches a CSS selector.
const element = document.querySelector('#myDiv.myClass');

5) querySelectorAll:

This method selects all elements that match a CSS selector and returns them as a
NodeList (or an array-like object).

const elements = document.querySelectorAll('.myClass');

.............................................................

How to apply styles using javascript:

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
<style>
.red {
color: red;
}

.bold {
font-weight: bold;
}
</style>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<p class="myClass">Paragraph 1</p>
<p class="myClass">Paragraph 2</p>
<div>
<span>Span 1</span>
<span>Span 2</span>
</div>
<script src="./index.js"></script>
</body>
</html>

js File:

const titleElement = document.getElementById('title');


const paragraphs = document.getElementsByClassName('myClass');

// Apply styles to the elements


titleElement.style.color = 'blue';
titleElement.style.fontSize = '24px';

for (let i = 0; i < paragraphs.length; i++) {


paragraphs[i].classList.add('red', 'bold');
}

.................................................................

Form Validation:
Html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>Form Validation Example</h1>
<form id="myForm" > <label for="name">Name:</label>
<input type="text" id="name" required>
<span id="nameError" class="error"></span>
<br>
<label for="email">Email:</label>
<input type="email" id="email" required>
<span id="emailError" class="error"></span>
<br>
<input type="submit" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>

JS File:

function validateForm(event) {
event.preventDefault(); // Prevent form submission

// Get form input values


const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');

// Get error message elements


const nameError = document.getElementById('nameError');
const emailError = document.getElementById('emailError');

// Clear previous error messages


nameError.textContent = '';
emailError.textContent = '';

// Perform validation
let isValid = true;

if (nameInput.value.trim() === '') {


nameError.textContent = 'Name is required';
isValid = false;
}

if (emailInput.value.trim() === '') {


emailError.textContent = 'Email is required';
isValid = false;
}

if (isValid) {
// Form is valid, submit or perform further actions
console.log('Form submitted');
// Here, you can submit the form using AJAX or perform any other desired
actions
}
}

.............................................................

Event Listners:
In JavaScript, event listeners are functions that wait for specific events to occur
on an HTML element, allowing you to respond to user interactions or other actions.
Here are some commonly used types of event listeners in JavaScript:

1) click Event Listener:


2) submit Event Listener:
3) mouseover and mouseout Event Listeners:
4) keydown and keyup Event Listeners:
5) change Event Listener:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
<style>
.active {
color: red;
}
</style>
</head>
<body>
<h1 id="myHeading">Click Me!</h1>

<script src="./index.js"></script>
</body>
</html>

js File:

const heading = document.getElementById('myHeading');

// Add event listener to the heading element


heading.addEventListener('click', function() {
heading.classList.add('active');
});
...........................................................

Event bubbling :

Event bubbling is a phenomenon in JavaScript where an event triggered on a


particular element propagates through its parent elements in the DOM hierarchy. The
event starts from the innermost element and "bubbles up" to its ancestors until it
reaches the root element.

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">

<style>
#outer {
border: 2px solid blue;
padding: 10px;
}

#inner {
border: 2px solid green;
padding: 10px;
}
</style>

</head>
<body>
<div id="outer">
<div id="inner">
<button id="button">Click Me!</button>
</div>
</div>

<script src="./index.js"></script>
</body>
</html>

Js File:

const outer = document.getElementById('outer');


const inner = document.getElementById('inner');
const button = document.getElementById('button');

// Add event listeners


outer.addEventListener('click', function(event) {
console.log('Outer div clicked');
});

inner.addEventListener('click', function(event) {
console.log('Inner div clicked');
});
button.addEventListener('click', function(event) {
console.log('Button clicked');
});

...........................................................

Event Capturing:

Event capturing is a phase in the event handling process where events are detected
and triggered starting from the top-most ancestor element and propagating down the
DOM hierarchy to the target element.

Html :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">

<style>
#outer {
border: 2px solid blue;
padding: 10px;
}

#inner {
border: 2px solid green;
padding: 10px;
}
</style>

</head>
<body>
<div id="outer">
<div id="inner">
<button id="button">Click Me!</button>
</div>
</div>

<script src="./index.js"></script>
</body>
</html>

JS File:

const outer = document.getElementById('outer');


const inner = document.getElementById('inner');
const button = document.getElementById('button');

// Add event listeners with capturing


outer.addEventListener('click', function(event) {
console.log('Outer div clicked (capturing)');
}, true);
inner.addEventListener('click', function(event) {
console.log('Inner div clicked (capturing)');
}, true);

button.addEventListener('click', function(event) {
console.log('Button clicked');
});

....................................................

stopPropagation() :
The stopPropagation() method is a built-in function in JavaScript that allows you
to stop the further propagation of an event through the DOM hierarchy. It is used
to prevent event bubbling or event capturing from continuing beyond the current
element.

Js file :
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');
const button = document.getElementById('button');

// Add event listeners


outer.addEventListener('click', function(event) {
console.log('Outer div clicked');
});

inner.addEventListener('click', function(event) {
console.log('Inner div clicked');
event.stopPropagation(); // Stop event propagation
});

button.addEventListener('click', function(event) {
console.log('Button clicked');
});

...................................................................

async and await :

async and await are keywords used to work with asynchronous operations in a more
synchronous-like manner.
They are part of the ES2017 (ES8) language specification and are commonly used in
modern JavaScript code.

async: The async keyword is used to define an asynchronous function. An


asynchronous function returns a Promise, which allows the function to pause
execution and resume later when an asynchronous operation is completed.

await: The await keyword can only be used inside an async function. It is used to
pause the execution of the function until a Promise is resolved or rejected. When
await is used with a Promise, it waits for the Promise to settle and then returns
the resolved value. Here's an example of using await:

async function fetchData() {


try {
const response = await fetch('https://api.instantwebtools.net/v1/airlines');//
The fetch() function returns a Promise
const data = await response.json(); // Wait for the Promise to resolve and get
the JSON data
console.log(data);
return data;
} catch (error) {
console.error(error);
}
}

fetchData();

You might also like