Important topics

This website contains More complex and important js topics

Get started
Go Back to basics

Browser object model(BOM)

·        The browser object model (BOM) is a programming interface that provides objects and methods to interact with browser window.

·        To access the properties of browser we have window object.

Window

·        Window: The top-level browser window object. It represents the entire browser window and provides methods and properties to control and interact with it.

·        console.log(window)

Window Object methods

·        To access the methods of window object there is no need of specifying window. each and every time.

·        Some of the methods of window object are –

alert()

·        The alert() method in JavaScript is used to display a dialog box with a specified message and an OK button. It is commonly used to provide users with information or to prompt them for input in a simple and straightforward manner. The syntax for the alert() method is as follows:

·        Syntax: alert(message)

·        Example

// alert("I am alert")

 

confirm()

·        The confirm() method in JavaScript is used to display a dialog box with a specified message and two buttons: OK and Cancel. It is commonly used to prompt users for a binary choice, typically to confirm or cancel an action. The syntax for the confirm() method is as follows:

·        Syntax: confirm(message)

·        Example

// confirm("Are You Sure?")

 

combining alert() and confirm()

// let a = confirm("I Love You")

// if(a){

// alert("I Love You Too")

//  }else{

// alert("I Hate You")

//  }

 

prompt()

·        The prompt() method in JavaScript is used to display a dialog box that prompts the user for input. It typically consists of a message, an input field, and two buttons: OK and Cancel. The user can input text into the field and then choose to submit or cancel the input.

·        The value collected from the user will be by default taken as String

·        Syntax: prompt(message)

·        Example

// prompt("Enter a number")

 

Converting to Number

//*1)

// let a = Number(prompt("Enter a Number"))

// console.log(a)

// console.log(typeof a)

 

//*2)

// let b = parseInt(prompt("Enter a number"))

// console.log(b)

// console.log(typeof b)

 

//*3)

// let b = parseFloat(prompt("Enter a number"))

// console.log(b)

// console.log(typeof b)

 

 

open()

·        In JavaScript, the open() method is used to open a new browser window or tab, or to navigate the current window to a new URL. It is commonly used to dynamically open new windows for various purposes such as displaying content, handling pop-up dialogs, or navigating to external links.

·        Syntax: open(url, target, features);

·        Example:

// let a;

// function opening(){

//    a=window.open("./Trail.html","Google","height=200px,width=200px,top=300px,left=800px")

// }

 

close()

·        In JavaScript, the close() method is used to close the current browser window or tab. It's typically invoked on the window object.

·        Example

// function closing(){

//   a.close()

// }

 

Height

 

innerHeight and outerHeight

 

·        innerHeight: This property represents the inner height of the browser window's content area in pixels. It includes the height of the viewport but excludes the height of any browser chrome (such as toolbars and scrollbars). This property is useful for determining the available space for displaying content within the viewport.

// console.log(`Inner Height : ${window.innerHeight}`)

 

·        outerHeight: This property represents the outer height of the browser window in pixels. It includes the height of the viewport as well as any additional browser chrome (such as toolbars and scrollbars). This property gives the total height of the browser window including its chrome.

// console.log(`Outer Height : ${window.outerHeight}`)

 

 

innerWidth and outerWidth

·        innerWidth: Similar to innerHeight, this property represents the inner width of the browser window's content area in pixels. It includes the width of the viewport but excludes the width of any browser chrome. It's useful for determining the available space for displaying content horizontally within the viewport.

// console.log(`Inner Width : ${window.innerWidth}`)

 

·        outerWidth: Similar to outerHeight, this property represents the outer width of the browser window in pixels. It includes the width of the viewport as well as any additional browser chrome. This property gives the total width of the browser window including its chrome.

// console.log(`Outer Width : ${window.outerWidth}`)

 

 

Web Storage Systems

·        localStorage and sessionStorage are two mechanisms provided by modern web browsers to store key-value pairs locally within the user's browser

 

 

LocalStorage

·        localStorage: The data stored in localStorage persists even after the browser is closed and reopened. It remains available until explicitly cleared by the user or the web application that stored the data.

·        Methods of Local Storage are:

 

//*setItem()

// localStorage.setItem("userId","rahul123")

// localStorage.setItem("password","rahul123")

// localStorage.setItem("age",23)

 

//*getItem()

// let a = localStorage.getItem("age")

// console.log(a)

// let b = localStorage.getItem("password")

// console.log(b)

 

//*removeItem()

// localStorage.removeItem("age")

 

//*clear()

// localStorage.clear()

 

 

sessionStorage()

·        sessionStorage: The data stored in sessionStorage is scoped to the current browser tab or window session. It persists only as long as the tab or window is open. When the tab or window is closed, the data is deleted.

 

·        Methods of Session Storage are:

 

//*setItem()

// sessionStorage.setItem("name","Rahul")

// sessionStorage.setItem("age",23)

// sessionStorage.setItem("place","Hyderabad")

 

//*getItem()

// let a = sessionStorage.getItem("age")

// console.log(a)

 

//*removeItem()

// sessionStorage.removeItem("place")

 

//*clear()

// sessionStorage.clear()

 

History

·        history: Represents the browser's history stack, allowing you to navigate backward and forward through the user's browsing history.

// console.log(window.history)

 

length

// console.log(window.history.length)

 

forward()

// function movingForward(){

//     window.history.forward()

// }

 

 

back()

// function movingBackward(){

//     window.history.back()

// }

 

 

go() -- movingForward

// function goForward(){

//     window.history.go(2)

// }

   

go() -- movingBackward

// function goBackward(){

//     window.history.go(-2)

// }

 

Screen

·        screen: Represents the user's screen and provides information about its size, color depth, and pixel depth.

// console.log(screen)

 

height and width

// console.log(screen.height)

// console.log(screen.width)

 

availHeight and availWidth

// console.log(screen.availHeight)

// console.log(screen.availWidth)

 

colorDepth and pixelDepth

// console.log(screen.colorDepth)

// console.log(screen.pixelDepth)

 

 

Location

// console.log(location)

// console.log(location.host)

// console.log(location.hostname)

// console.log(location.href)

// console.log(location.port)

// console.log(location.protocol)

 

// function display11(){

//     location.reload()

// }

 

// function display12(){

//     location.assign("https://www.w3schools.com/")

// }

 

// function display13(){

//     location.replace("https://www.flipkart.com/")

// }

 

// function display14(){

//     location.href="https://www.amazon.in/"

// }

 

Navigator

 

// console.log(navigator.appName)

// console.log(navigator.appCodeName)

// console.log(navigator.language)

// console.log(navigator.languages)

// console.log(navigator.cookieEnabled)

// console.log(navigator.onLine)

 

·        To know the location of the user

// navigator.geolocation.getCurrentPosition((pos)=>{

//   console.log(Latitude : ${pos.coords.latitude})

//   console.log(Longitude : ${pos.coords.longitude})

// })

 

 


DOCUMENT OBJECT MODEL(DOM)

·        When our browser renders our html page it creates a tree like sturucture interally knows "DOM"

·        DOM is a standard for how to get, change, add, or delete HTML elements.

 

//!Document Object

// console.log(window)

// console.log(document)

// console.dir(document)

 

Direct Access

 

// console.log(document.all)

// console.log(document.head)

// console.log(document.body)

// console.log(document.links)

// console.log(document.images)

// console.log(document.forms)

 

Indirect Access

 

·        To access a html element through javascript we have 6 different ways

 

1.     getElementById()

·        getElementById is a method in JavaScript that allows you to access an HTML element in a document by its unique id attribute

 

// let h1 = document.getElementById("target")

// console.log(h1)

// console.dir(h1)

// h1.style.color="yellow"

// h1.style.backgroundColor="green"

// h1.style.border="2px solid red"

 

// let p = document.getElementById("para")

// console.log(p)

 

2.     getElementsByClassName()

·        getElementsByClassName is another method in JavaScript that allows you to select elements in the DOM based on their class names. This method returns a live HTMLCollection of all elements in the document that have the specified class name

// let data = document.getElementsByClassName("something")

// console.log(data)

// console.dir(data)

 

// let newData = Array.from(data)

// console.log(newData)

// newData.map((val)=>{

//    val.style.color="goldenrod"

//    val.style.backgroundColor="hotpink"

// })

 

3.     getElementsByTagName()

·        getElementsByTagName() is a method in JavaScript that allows you to select elements in the DOM based on their tag name. This method returns a live HTMLCollection of all elements in the document that have the specified tag name.

// let headings = document.getElementsByTagName("h1")

// console.log(headings)

 

// let newArray = Array.from(headings)

// console.log(newArray)

// newArray.map((element)=>{

//    element.style.fontSize="10px"

// })

 

4.     getElementsByName()

·        getElementsByName() is a method in JavaScript that allows you to select elements in the DOM based on their name attribute. This method returns a live NodeList of all elements in the document that have the specified name attribute.

// let inputs = document.getElementsByName("firstName")

// console.log(inputs)

// inputs.forEach((element)=>{

//     element.style.padding="20px"

// })

5.     querySelector()

·        querySelector() is a method in JavaScript that allows you to select the first element within the document that matches a specified CSS selector.

 

·        Passing ID

// let output = document.querySelector("#target")

// console.log(output)

// output.style.backgroundColor="red"

 

·        Passing CLASS

// let output= document.querySelector(".something")

// console.log(output)

// output.style.backgroundColor="red"

 

 

·        /Passing TAGNAME

// let output= document.querySelector("h1")

// console.log(output)

 

·        Passing COMBINATION

 

// let output = document.querySelector("div p")

// console.log(output)

// output.style.backgroundColor="lightblue"

// output.style.color="brown"

 

6.     querySelectorAll()

·        querySelectorAll() is a method in JavaScript that allows you to select all elements within the document that match a specified CSS selector. This method returns a static NodeList containing references to all matching elements.

 

·        Passing ID

// let output = document.querySelectorAll("#target")

// console.log(output)

// output.forEach((ele)=>{

//    ele.style.color="green"

// })

 

·        Passing CLASS

// let output = document.querySelectorAll(".something")

// console.log(output)

// output.forEach((ele)=>{

//    ele.style.color="green"

// })

 

·        Passing TAGNAME

// let output = document.querySelectorAll("h1")

// console.log(output)

// output.forEach((ele)=>{

//    ele.style.color="green"

// })

 

·        Passing COMBINATION

// let output = document.querySelectorAll("div p")

// console.log(output)

// output.forEach((ele)=>{

//    ele.style.color="green"

// })

 

Difference between queryselector() and queryselectorall()

·        querySelector() is used when you need to select a single element or the first element that matches a CSS selector, while querySelectorAll() is used when you need to select multiple elements that match the CSS selector.

 

write and writeln

·        write() and writeln() methods are used to write content to the HTML document. However, they differ in how they handle line breaks

 

write()

·        The write() method writes the specified content to the document without appending a newline character at the end.

// document.write("I am From Javascript Dom")

// document.write("I am From Javascript Dom")

// document.write("<h1>I am From Javascript Dom</h1>")

 

writeln()

·        The writeln() method writes the specified content to the document appending a newline character at the end.

 

// document.writeln("I am From Javascript Dom")

// document.write("I am From Javascript Dom")

// document.writeln("<h1>I am From Javascript Dom</h1>")

 

// document.writeln("<div><h1>Hello</h1></div>")

 

Accessing Text inside Html Element (innerText,innerHTML,textContent)

innerText -- can access only content which is visble on the ui.

innerHTML -- can access all the html Structure along with the text Content inside it.

textContent -- can access all the content if it is hidden.


1)

// let h1 = document.querySelector("#target")

// console.log(h1)

// console.log(InnerText : ${h1.innerText})

// console.log(InnerHTML : ${h1.innerHTML})

// console.log(textContent : ${h1.textContent})

 2)

// let div = document.querySelector("div")

// console.log(div)

// console.log(InnerText : ${div.innerText})

// console.log(InnerHTML : ${div.innerHTML})

// console.log(textContent : ${div.textContent})

 

Setting text inside html elements


// let section = document.getElementById("container")

// console.log(section)

 

// section.innerText = "Helloooooooo from InnerText" //*Cannot Pass Tags

 

// section.innerHTML="<h1>Helllooooo from innerHTML</h1>"

 

// section.textContent = "Helloooooooooooo from textContent" //*Cannot Pass Tags

 

// section.innerHTML = `

// <h1 style="background-color:green;color:yellow;text-align:center">I am From InnerHTML</h1>

// <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos placeat neque officia dolorum nihil pariatur aperiam nam, hic nisi consequatur exercitationem amet, porro sequi vitae earum praesentium sed dolores doloribus a? Cupiditate hic eos aperiam cum. Quia culpa voluptatibus obcaecati voluptatum consequuntur minus autem optio quas magnam maiores eos, ipsa unde ex. Inventore neque quos excepturi cupiditate magnam illum voluptates facilis, eius sapiente illo libero quae optio, dolor quam cum culpa? Mollitia, dolorum voluptate.</p>

// <button>Submit</button>

// `

 


Getting Atrributes

// let section = document.querySelector("#container")

// console.log(section)

// section.innerHTML = "<h1>I am Here Only</h1>"

 

·        getAttribute() and getAttributeNode() are methods used to retrieve attribute values of an HTML element, but they serve slightly different purposes

·        the getAttribute() method is used to retrieve the value of a specific attribute of an HTML element.
// let ouput1 = section.getAttribute("id")

// console.log(ouput1)

 

//#The getAttributeNode() method is used to retrieve the attribute node itself, rather than just its value.

// let output2 = section.getAttributeNode("style")

// let output3 = section.getAttributeNode("style").value

// console.log(output2)

// console.log(output3)

·        In JavaScript, the attributes property of an HTML element provides access to a collection of all the attributes of that element. This collection is represented as a NamedNodeMap, which is similar to an array but contains nodes with key-value pairs representing attributes.



// let output4 = section.attributes

// console.log(output4)

 

//!Setting the attributes.

// let section = document.getElementById("container")

// console.log(section)

setAttribute()

·         In JavaScript, setAttribute is a method that allows you to set an attribute on a specified element in the HTML DOM (Document Object Model). It is primarily used to dynamically add or modify attributes of HTML elements.

//*syntax for using setAttribute:

//*element.setAttribute(attribute, value);

 

// section.setAttribute("class","stupid original")

// section.setAttribute("style","background-color:yellow")

// section.setAttribute("rahul","webTech")

 

 

·        removeAttribute()


In JavaScript, removeAttribute is a method used to remove a specified attribute from an HTML element in the DOM (Document Object Model). This method is commonly used to dynamically manipulate the attributes of HTML elements.

 

//* syntax for using removeAttribute:

//*element.removeAttribute(attribute);

// section.removeAttribute("style")

// section.removeAttribute("title")

 

className -- fetches the name of the class of the targeted element
// let store = section.className

// console.log(store)

// }

 

classList
In JavaScript, the classList property provides an interface to manipulate the classes of an HTML element. It offers a convenient way to add, remove, toggle, and check for the presence of CSS classes on an element.

//*add(class1, class2, ...): Adds one or more classes to the element. If the class is already present, it will not add it again.
//*remove(class1, class2, ...): Removes one or more classes from the element.

//*toggle(class, force): Toggles the presence of a class. If the class is present, it removes it; if it's absent, it adds it.

//*contains(class): Checks if the element has a specific class. Returns true if the class is present, false otherwise.

//*item(index): Returns the class name at the specified index. This is useful when you want to access a class by its position.

//*length: Returns the number of classes on the element.

// let section = document.getElementById("container")

 

 function handler(){
// section.classList.add("firstCopy","secondCopy")

// section.classList.replace("duplicate","fake")

// section.classList.replace("original","genuine")

// section.classList.replace("original","duplicate")

// section.classList.remove("duplicate","original")

// section.classList.toggle("newClass")

// let val = section.classList.contains("firstCopy")

// console.log(val)

// let val = section.classList.length

// console.log(val)

// let val = section.classList.item(3)

// console.log(val)

// }

// console.log(section.classList)

 


createElement
-used to dynamically create HTML elements.

// Syntax:document.createElement(tagName)

// let article = document.createElement("article")

// console.log(article)

// let h1 = document.createElement("h1")

// console.log(h1)

// let p = document.createElement("p")

// console.log(p)

// let button = document.createElement("button")

// console.log(button)

 


createTextNode
-createTextNode method is used to create a new text node. Text nodes are used to represent textual content within HTML elements.
//*Syntax:document.createTextNode(text)

// let articleText = document.createTextNode("I am Article")

// console.log(articleText)

 

// let h1Text = document.createTextNode("I am Heading")

// console.log(h1Text)

 

// let pText = document.createTextNode("Lorem ipsum dolor sit, amet consectetur adipisicing elit. Fugit voluptatum, exercitationem omnis in magnam est odit eaque qui ea ratione illum excepturi laboriosam non ducimus velit veritatis nisi id repellendus.")

// console.log(pText)

 

// let buttonText = document.createTextNode("Click")

// console.log(buttonText)

 


appendChild
-appendChild is a method used to append a single node (element, text node, etc.) as the last child of a parent node.

// article.appendChild(articleText)

// console.log(article)

 

// h1.appendChild(h1Text)

// console.log(h1)

 

// p.appendChild(pText)

// console.log(p)

 

// button.appendChild(buttonText)

// console.log(button)

 

append()
-append is a newer method introduced in JavaScript, and it is used to append one or more nodes or DOMString objects to a parent node.

// let body = document.body

// console.log(body)

// body.append(article, h1, p, button)

 


createComment
-createComment method is used to create a comment node in the HTML DOM (Document Object Model). Comment nodes are used to insert comments into the HTML structure, which are not rendered by the browser but can be useful for adding notes or annotations to the HTML code.


//*Syntax:document.createComment(text)

// let comment1 = document.createComment("I am Comment Through js DOM")

// console.log(comment1)

 

// let comment2 = document.createComment("I am Comment Again") > Rahul S: console.log(comment2)

// body.append(comment1, comment2)

 


insertBefore()
-insertBefore is a method used to insert a new node before an existing child node of a specified parent node in the HTML DOM (Document Object Model). This method provides a way to dynamically insert elements or nodes at specific positions within a parent node's children.

//*Syntax:parentNode.insertBefore(newNode, referenceNode);

 

// body.insertBefore(button,article)

// body.insertBefore(h1,button)

// body.insertBefore(comment1,h1)

 

 


EVENTS

·        Events are actions or occurrences that happen as a result of user interaction or other activities in a web page or web application. These interactions can include things like clicking on an element, hovering over it with the mouse, submitting a form, pressing a key on the keyboard

// let h1 = document.querySelector("h1")

// let p = document.querySelector("p")

// let btn = document.getElementById("btn")

// let btn2 = document.querySelector("#btn2")

// function display(){

//     h1.innerText = "Good Morning"

    // document.write("Hello")

// }

 

// function change(){

//     p.style.color="yellow"

//     p.style.backgroundColor="green"

// }

 

// function something(){

//     console.log("GOOD NIGHT")

// }

// btn.onclick=something()

 

·        addEventListener is a method in JavaScript used to attach an event handler to an element. It allows you to specify a function (event listener) that should be executed when a particular event occurs on the target element.

 

//*Syntax:element.addEventListener(event, function, useCapture);

 

 

// btn2.addEventListener("click",()=>{

//     console.log("I LOVE YOU")

// })

 

 

 

mouseenter

·        The mouseenter event in JavaScript occurs when the mouse cursor enters the boundaries of an element.

// let h1 = document.querySelector("h1")

// let p = document.querySelector("p")

// let button = document.querySelector("button")

 

// h1.addEventListener("mouseenter",(e)=>{

//     console.log(e)

//     console.log("Hovered upon h1")

// })

 

// p.addEventListener("mouseenter",()=>{

//     p.style.color="red"

//     p.style.backgroundColor="black"

//     p.style.fontSize = "32px"

// })

 

// button.addEventListener("mouseenter",()=>{

//     button.style.padding="7px 14px"

// })

 

dblclick

·        The dblclick event in JavaScript occurs when a user double-clicks on an element using the mouse. This event is triggered when two consecutive click events happen within a short time interval on the same element.

// let btn = document.querySelector("button")

// btn.addEventListener("dblclick",()=>{

//     console.log("yOU dOUBLE cLICKED")

// })

change

·        The change event in JavaScript occurs when the value of an <input>, <select>, or <textarea> element has been changed by the user.             let input = document.querySelector("input")

// let select = document.querySelector("select")

// let textarea = document.querySelector("textarea")

// console.log(input)

// console.log(select)

// console.log(textarea)

 

// input.addEventListener("change",()=>{

//     input.style.color="white"

//     input.style.backgroundColor="black"

// })

// select.addEventListener("change",()=>{

//     select.style.color="white"

//     select.style.backgroundColor="black"

// })

// textarea.addEventListener("change",()=>{

//     textarea.style.color="white"

//     textarea.style.backgroundColor="black"

// })

 

input

·        The input event in JavaScript occurs whenever the value of an <input>, <textarea>, or <select> element changes as the user interacts with it. Unlike the change event, which fires when the element loses focus after its value has changed, the input event fires immediately when the value of the element is modified.

// let input = document.querySelector("input")

// input.addEventListener("input",()=>{

//     input.style.backgroundColor="black"

//     input.style.color="white"

// })

   

 keypress,keydown,keyup

·        The keypress, keydown, and keyup events in JavaScript are related to keyboard interactions.

 

·        KEYDOWN:This event occurs when a key on the keyboard is pressed down. It fires as soon as the key is pressed, and it will continue to fire repeatedly if the key is held down continuously.

 

·        KEYPRESS:It occurs when a key that produces a character value is pressed down

 

·        KEYUP:This event occurs when a key on the keyboard is released after being pressed. It fires once, regardless of how long the key was held down.

 

    // let input = document.querySelector("input")

 

// input.addEventListener("keypress",(e)=>{

//     console.log(e)

//     console.log(The key pressed is ${e.key})

//     console.log(e.code)

//     console.log(e.keyCode)

    // console.log("The Key is pressed")

// })

 

// input.addEventListener("keydown",()=>{

//     console.log("The Key is down")

// })

// input.addEventListener("keyup",()=>{

//     console.log("The Key is up")

// })

 


Event propagation

·        Event propagation refers to the process by which events are transmitted or propagated through the DOM (Document Object Model) hierarchy from the target element to its ancestors or descendants.

 

We have two phases in event propagation they are:

1)EVENT BUBBLING PHASE

2)EVENT CAPTURING PHASE

 

// let outer = document.getElementById("outer")

// let inner = document.getElementById("inner")

 

 

EVENT BUBBLING PHASE

·        If the event propagates from target element to parent element then it is in bubbling phase

·        can be achieved by setting third parameter of addeventlistener to false

 

// outer.addEventListener("click",()=>{

//     alert("OUTER BOX CLICKED")

// },false)

   

// inner.addEventListener("click",(event)=>{

//     alert("INNER BOX CLICKED")

//     event.stopPropagation()

// },false)

 

 

EVENT CAPTURING PHASE

·        If the event propagates from parent element to target element then it is in capturing phase

·        can be achieved by setting third parameter of addeventlistener to true

 

// outer.addEventListener("click",()=>{

//     alert("OUTER BOX CLICKED")

// },true)

   

// inner.addEventListener("click",()=>{

//     alert("INNER BOX CLICKED")

// },true)


Promises

·        Promises are Object used to handle asynchronous operations(those operations which take some time to perform the task)

Promises in JS have 3 states

1)Pending State

2)Resolved State

3)Rejected State

·        To handle the resolved state promise we have then() method similarly to handle catch method we have catch()

·        then() and catch() are higherOrderMethods which take the promise result of resolved and rejected Promises respectively

 

// let p = new Promise((resolve,reject)=>{

//     let meet = false;

//     if(meet){

//       resolve("Promise got resolved")

//     }else{

//         reject("Promise got rejected")

//     }

// })

// console.log(p)

 

// p.then((val)=>{

//     console.log(`${val} ,We will order something`)

// }).catch((err)=>{

//     console.log(`${err} ,Sorry I had some work`)

// })


 

FETCH()

·        The fetch method in JavaScript is used to make network requests to fetch resources (like JSON data, images, or any other files) from a server.

·        In Simpler Words , it helps us to extract the data from the api

Example:

// !handling promises using then

// let output=fetch("https://fakestoreapi.com/products")

// console.log(output);

// output.then((result)=>{

//     let finaloutput=result.json();// here we will get promise which we store in another variable and extract the promise fulfilled data using .then() methods again

//     finaloutput.then((result)=>{

//         console.log(result);

//     })

// })

 

//!short version of handling promise using then

// fetch("https://fakestoreapi.com/products")

// .then( result =>result.json())

// .then( result => console.log(result))

 


ASYNC AND AWAIT

·        async and await are keywords introduced in ECMAScript 2017 (ES8) that work together to simplify asynchronous JavaScript code

·        They help us to handle the promises gracefully

 

async - The async keyword is used to declare an asynchronous function. An asynchronous function returns a promise implicitly, which resolves to the value returned by the async function.

await - The await keyword can only be used inside an async function. It pauses the execution of the async function until the promise passed to await is settled.

 

.json()

·        .json() method is used when working with the fetch API or any other mechanism that returns a promise representing a response from a server. It is specifically used to extract the JSON body content from the response object, converting it into a JavaScript object that can be easily manipulated and used within your application.

Example:

//!handling promise using async and await

// let func= async ()=>{

//     let output=await fetch("https://fakestoreapi.com/products")

//     let anotheroutput=await output.json()

//     console.log(anotheroutput);

// }

// func()

// !adding api items to our document

// let func= async ()=>{

//     let output=await fetch("https://fakestoreapi.com/products")

//     let anotheroutput=await output.json()

        // console.log(anotheroutput);

//     let container=document.getElementById("container")

//     anotheroutput.forEach((element)=>{

//         container.innerHTML+=`

//         <main id="item">

//         <h1>${element.id}</h1>

//         <h1>${element.title}</h1>

//         <img src=${element.image}>

//         <p>${element.description}</p>

//         <h1>${element.price}</h1>

//        </main>

 

//         `

//     })

// }

// func()

 


ADDEVENTLISTENER

·        addEventListener is a method in JavaScript used to attach an event handler function to an element, so that the function is executed when a specific event occurs on that element.

Syntax:
element.addEventListener(event, function, useCapture);

o   element: The HTML element to which you want to attach the event listener.

o   event: A string representing the event type (e.g., "click", "mouseover", "keydown").

o   function: The function to be executed when the event occurs.

o   useCapture (optional): A boolean value indicating whether to use event capturing (true) or event bubbling (false). Defaults to false if not specified.

Example:

// const button = document.getElementById('btn');

// button.addEventListener('click', ()=>{

//     alert('Button clicked!');

// );


PREVENT DEFAULT

·        The preventDefault method in JavaScript is used to prevent the default action of an event from occurring.

·        This is particularly useful when handling form submissions to control the behavior of the browser when a form is submitted.

Example:

// const form = document.querySelector('form');

// form.addEventListener('submit',(event)=>{

//     event.preventDefault();

// }

 


isNaN()

·        The isNaN method in JavaScript is used to determine whether a value is NaN (Not-a-Number). It returns true if the value is NaN, and false otherwise.

Syntax:isNaN(value)

Example:

// isNaN(NaN); // true

// isNaN(123); // false

// isNaN('123'); // false (automatically converts string to number)

// isNaN('Hello'); // true (cannot convert 'Hello' to a number)

 

 


Form Validation

 

 

// let form=document.querySelector("form")

// form.addEventListener("submit",(e)=>{

//     e.preventDefault()

//     let name=document.getElementById("name")

//     let phone=document.getElementById("phone")

//     let password=document.getElementById("password")

//     let cpassword=document.getElementById("cpassword")

    // console.log(name.value);

    // console.log(phone.value);

    // console.log(password.value);

    // console.log(cpassword.value);

//     let finalname=(name.value);

//     let finalphone=(phone.value);

//     let finalpassword=(password.value);

//     let finalcpassword=(cpassword.value);

 

//     //!name field validation

 

//     if(finalname.length<3 ||finalname.length>10){

//         alert("please enter charecters between 3 and 10")

//     }

 

//     //!password field validation

//     if(finalpassword!=finalcpassword){

//         alert("please check the password")

//     }

 

//     //!phone field validation

//     if(isNaN(finalphone)){

//         alert("enter correct phone number")

//     }

 

    // let numbervalue=isNaN(phone)

    // if(numbervalue){

    //     alert("please enter proper value")

    // }//as per sir

// })

 

// let eye = document.getElementById("eye")

// let password=document.getElementById("password")

// let passwordvisible=false;

// eye.addEventListener("click",()=>{

//     if(passwordvisible){

//         password.type="password"

//         passwordvisible=false

//     }

//     else{

//         password.type="text"

//         passwordvisible=true

//     }

// })

 

// let eye2 = document.getElementById("eye2")

// let password1=document.getElementById("cpassword")

// let passwordvisible1=false;

// eye2.addEventListener("click",()=>{

//     if(passwordvisible1){

//         password1.type="password"

//         passwordvisible1=false

//     }

//     else{

//         password1.type="text"

//         passwordvisible1=true

//     }

// })