[go: up one dir, main page]

0% found this document useful (0 votes)
66 views38 pages

Module-02 FSD (BIS601)

The document provides an overview of the Document Object Model (DOM) in web development, detailing how JavaScript and jQuery can be used to manipulate HTML elements. It covers selecting, modifying, adding, removing elements, handling events, changing CSS styles, and AJAX for data fetching. Additionally, it discusses event delegation, form handling, and various types of events, along with examples for practical implementation.

Uploaded by

kannika.dg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views38 pages

Module-02 FSD (BIS601)

The document provides an overview of the Document Object Model (DOM) in web development, detailing how JavaScript and jQuery can be used to manipulate HTML elements. It covers selecting, modifying, adding, removing elements, handling events, changing CSS styles, and AJAX for data fetching. Additionally, it discusses event delegation, form handling, and various types of events, along with examples for practical implementation.

Uploaded by

kannika.dg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

BIS601|FULLSTACKDEVELOPMENT

Module-02

Document Object Model

1. Introduction to DOM

 DOM(DocumentObjectModel)representsthestructureofanHTML
document as a tree of objects.

 JavaScriptcanaccessandmanipulatetheseelementsdynamically.

2. SelectingElementsinDOM

 UsingJavaScript:

o document.getElementById("id")–Selectsanelementby ID.

o document.getElementsByClassName("class")–Selectselementsby
class.

o document.getElementsByTagName("tag")–Selectselementsbytag
name.

o document.querySelector("selector")–Selectsthefirstmatching
element.

o document.querySelectorAll("selector")–Selectsallmatching
elements.

 UsingjQuery:

o $("selector")–SelectselementsusingCSS-likesyntax.

Dept of ISE, RIT, Hassan Page1


BIS601|FULLSTACKDEVELOPMENT

3. ModifyingElements

 JavaScript:

o element.innerHTML="NewContent";–Changescontentinsidean
element.

o element.textContent="NewText";–Updatesonlytextcontent.

o element.setAttribute("attribute","value");–Modifiesattributes.

 jQuery:

o $("selector").html("NewContent");

o $("selector").text("NewText");

o $("selector").attr("attribute","value");

4. Adding&RemovingElements

 JavaScript:

o document.createElement("tag")–Createsanewelement.

o parent.appendChild(child)–Addsachildelement.

o parent.removeChild(child)–Removesanelement.

 jQuery:

o $("parent").append("<tag>NewContent</tag>");

o $("parent").prepend("<tag>NewContent</tag>");

o $("selector").remove();

Dept of ISE, RIT, Hassan Page2


BIS601|FULLSTACKDEVELOPMENT

5. HandlingEvents

 JavaScript:

o element.addEventListener("event",function);

 jQuery:

o $("selector").on("event",function(){});

 Example:

document.getElementById("btn").addEventListener("click",function(){

alert("ButtonClicked!");

});

$("#btn").on("click",function()

{ alert("Button Clicked!");

});

6. ChangingCSSStyles

 JavaScript:

o element.style.property="value";

 jQuery:

o $("selector").css("property","value");

 Example:

Dept of ISE, RIT, Hassan Page3


BIS601|FULLSTACKDEVELOPMENT

document.getElementById("box").style.backgroundColor="blue";

$("#box").css("background-color","blue");

7. Animations&EffectsinjQuery

 $("selector").fadeIn();

 $("selector").fadeOut();

 $("selector").slideUp();

 $("selector").slideDown();

 $("selector").animate({property:"value"},duration);

8. AJAXandFetchingData

 JavaScriptFetchAPI:

fetch("url")

.then(response=>response.json())

.then(data=>console.log(data));

 jQueryAJAX:

$.ajax({

url:"url",

method:

"GET",success:function

(data){

console.log(data);
Dept of ISE, RIT, Hassan Page4
BIS601|FULLSTACKDEVELOPMENT

});

9. EventDelegation

 Usedforhandlingeventsdynamicallyonelementsthatmaynotexistatthe start.

 JavaScript:

document.getElementById("parent").addEventListener("click",function(event)

{ if (event.target.matches(".child")) {

console.log("Childclicked!");

});

 jQuery:

$("#parent").on("click",".child",function()

{ console.log("Child clicked!");

});

10. FormHandling&Validation

 Accessingformvalues:

letinputValue=document.getElementById("input").value;

let inputValue = $("#input").val();

Dept of ISE, RIT, Hassan Page5


BIS601|FULLSTACKDEVELOPMENT

 Validating input fields:

if(inputValue.trim()===""){

alert("Fieldcannotbeempty");

1. DOMNode

 AnodeisanyobjectintheDOMtree,suchas:

o Elementnodes(<div>,<p>,<button>,etc.)

o Attributenodes(class,id,style)

o Textnodes(contentinsideanelement)

o Commentnodes(<!--Thisisacomment-->)

2. AccessingNodes

Using JavaScript

 document.getElementById("id")→Selectsanelementby ID.

 document.getElementsByClassName("class")→Selectselementsbyclass
name.

 document.getElementsByTagName("tag")→Selectselementsbytagname.

 document.querySelector("selector")→Selectsthefirstmatchingelement.

 document.querySelectorAll("selector")→Selectsallmatchingelements.

Dept of ISE, RIT, Hassan Page6


BIS601|FULLSTACKDEVELOPMENT

UsingjQuery

 $("selector")→SelectselementsusingCSS-likesyntax.

Example:

letnode=document.getElementById("demo");//JavaScript

let node = $("#demo"); // jQuery

3. Creating&AddingNodes

Using JavaScript

 document.createElement("tag")→Createsanewelement.

 parent.appendChild(child)→Appendsachildnodetoaparent.

 parent.insertBefore(newNode,existingNode)→Insertsbeforeanothernode.

Example:

letnewDiv=document.createElement("div");

newDiv.textContent = "New Element";

document.body.appendChild(newDiv);

UsingjQuery

 $("parent").append("<div>NewElement</div>");

 $("parent").prepend("<div>NewatStart</div>");

Dept of ISE, RIT, Hassan Page7


BIS601|FULLSTACKDEVELOPMENT

Example:

$("body").append("<div>NewElement</div>");

4. Removing&ReplacingNodes

Using JavaScript

 parent.removeChild(child)→Removesanode.

 parent.replaceChild(newNode,oldNode)→Replacesanode.

Example:

lettoRemove=document.getElementById("remove"

);

toRemove.parentNode.removeChild(toRemove);

Using jQuery

 $("selector").remove();→Removesanelement.

 $("selector").replaceWith("<newelement>");→Replacesanelement.

Example:

$("#remove").remove();

$("#old").replaceWith("<p>NewParagraph</p>");

Dept of ISE, RIT, Hassan Page8


BIS601|FULLSTACKDEVELOPMENT

5. Cloning&CopyingNodes

Using JavaScript

 element.cloneNode(true)→Clonesanelementwithallchildren(true)or only
itself (false).

Example:

letoriginal=document.getElementById("original"); let

clone = original.cloneNode(true);

document.body.appendChild(clone);

UsingjQuery

 $("selector").clone();

Example:

letclonedElement=$("#original").clone();

$("body").append(clonedElement);

Dept of ISE, RIT, Hassan Page9


BIS601|FULLSTACKDEVELOPMENT

6. NavigatingNodes(Parent,Child,Sibling)

Using JavaScript

 element.parentNode→Getstheparentnode.

 element.children→Getsallchildelements.

 element.firstChild/element.lastChild→Getsthefirst/lastchild.

 element.nextSibling/element.previousSibling→Getsthenext/previous
node.

Example:

let parent = document.getElementById("child").parentNode;

letfirstChild=document.getElementById("parent").firstChild;

Using jQuery

 $("selector").parent();

 $("selector").children();

 $("selector").first();

 $("selector").next();

Example:

letparent = $("#child").parent();

letfirstChild=$("#parent").children().first();

Dept of ISE, RIT, Hassan Page10


BIS601|FULLSTACKDEVELOPMENT

7. ChangingNodeContent

Using JavaScript

 element.innerHTML="NewContent";→Changesinnercontent.

 element.textContent="NewText";→Changestextonly.

UsingjQuery

 $("selector").html("NewContent");

 $("selector").text("NewText");

Example:

document.getElementById("demo").innerHTML="UpdatedContent";

$("#demo").html("UpdatedContent");

8. ChangingNodeAttributes

Using JavaScript

 element.setAttribute("attribute","value");

 element.getAttribute("attribute");

 element.removeAttribute("attribute");

UsingjQuery

 $("selector").attr("attribute","value");

 $("selector").removeAttr("attribute");

Dept of ISE, RIT, Hassan Page11


BIS601|FULLSTACKDEVELOPMENT

Example:

document.getElementById("demo").setAttribute("class","new-class");

$("#demo").attr("class","new-class");

1. UpdatingElementContent

 innerHTML(JS)/.html()(jQuery)→ChangestheinnerHTML,
including formatting.

 textContent(JS)/.text()(jQuery)→Updatestextcontentonly(ignores
HTML tags).

 Example:

document.getElementById("demo").innerHTML="<b>BoldText</b>";//
JavaScript

$("#demo").html("<b>BoldText</b>");//jQuery

2. UpdatingElementAttributes

 setAttribute("attr","value")(JS)/.attr("attr","value")(jQuery)→
Modifies an attribute.

 getAttribute("attr")(JS)/.attr("attr")(jQuery)→Retrievesanattribute
value.

 removeAttribute("attr")(JS)/.removeAttr("attr")(jQuery)→Deletes an
attribute.

Dept of ISE, RIT, Hassan Page12


BIS601|FULLSTACKDEVELOPMENT

 Example:

document.getElementById("myImage").setAttribute("src","new.jpg");//
JavaScript

$("#myImage").attr("src","new.jpg");//jQuery

3. HandlingEvents

 JavaScript:addEventListener("event",function)→Bindsaneventtoan
element.

 jQuery:.on("event",function)→Bindsanevent(canhandlemultiple
events).

 Commonevents:click,mouseover,keydown,change.

 Example:

document.getElementById("btn").addEventListener("click",function(){

alert("Clicked!");

});

$("#btn").on("click",function(){

alert("Clicked!");

});

Dept of ISE, RIT, Hassan Page13


BIS601|FULLSTACKDEVELOPMENT

4. RemovingEventListeners

 JavaScript:removeEventListener("event",function)

 jQuery:.off("event")

 Example:

document.getElementById("btn").removeEventListener("click",myFunction);

$("#btn").off("click");

DifferentTypesofEventsinJavaScript& jQuery

EventsinJavaScriptandjQueryallowdeveloperstohandleuserinteractions effectively.
Below are the key types of events:

1. MouseEvents⬛'

Theseeventsrespondtouseractionswiththemouse.

Dept of ISE, RIT, Hassan Page14


BIS601|FULLSTACKDEVELOPMENT

document.getElementById("btn").addEventListener("click",function()

{ alert("Button clicked!");

});

//jQuery

$("#btn").on("click",function()

{ alert("Button clicked!");

});

2. KeyboardEvents.

Theseeventsrespondtokeyboardinteractions.

document.addEventListener("keydown",function(event)

{ console.log("Key pressed: " + event.key);

});

Dept of ISE, RIT, Hassan Page15


BIS601|FULLSTACKDEVELOPMENT

//jQuery

$(document).on("keydown",function(event)

{ console.log("Key pressed: " + event.key);

});

3. FormEvents)‘¸•

Theseeventsarerelatedtoformelements.

document.getElementById("myForm").addEventListener("submit",
function(event) {

event.preventDefault();//Preventsformfromsubmitting

alert("Form submitted!");

});

//jQuery

$("#myForm").on("submit",function(event){

event.preventDefault();

Dept of ISE, RIT, Hassan Page16


BIS601|FULLSTACKDEVELOPMENT

alert("Formsubmitted!");

});

4. WindowEvents●?

Theseeventsaretriggeredbythebrowserwindow.

window.addEventListener("resize",function()

{ console.log("Window resized!");

});

//jQuery

$(window).on("resize",function()

{ console.log("Windowresized!");

});

Dept of ISE, RIT, Hassan Page17


BIS601|FULLSTACKDEVELOPMENT

5. ClipboardEvents|,¯–−⬛

Theseeventshandlecopyingandpastingactions.

document.addEventListener("copy",function()

{ alert("Content copied!");

});

//jQuery

$(document).on("copy",function()

{ alert("Content copied!");

});

6. Drag&DropEvents⬛'.çv†

Theseeventsallowuserstodraganddropelements.

Dept of ISE, RIT, Hassan Page18


BIS601|FULLSTACKDEVELOPMENT

document.getElementById("dragElement").addEventListener("dragstart",
function() {

console.log("Draggingstarted!");

});

//jQuery

$("#dragElement").on("dragstart",function()

{ console.log("Dragging started!");

});

7. MediaEvents`~fz’˘ˆ—˜

Theseeventsareusedformediaelementslike<audio>and<video>.

document.getElementById("myVideo").addEventListener("play",function(){

Dept of ISE, RIT, Hassan Page19


BIS601|FULLSTACKDEVELOPMENT

console.log("Videostartedplaying!");

});

//jQuery

$("#myVideo").on("play", function()

{ console.log("Videostartedplaying!");

});

8. TouchEvents(MobileDevices)_ˆ□

Theseeventshandletouchinteractionsonmobiledevices.

document.addEventListener("touchstart",function()

{ console.log("Screen touched!");

});

//jQuery

Dept of ISE, RIT, Hassan Page20


BIS601|FULLSTACKDEVELOPMENT

$(document).on("touchstart",function()

{ console.log("Screen touched!");

});

1. UsingJavaScript(addEventListener)

 TheaddEventListener(event,function)methodisusedtobindaneventtoan
element.

 Syntax:

element.addEventListener("event",function);

 Example:

document.getElementById("btn").addEventListener("click",function(){

alert("Buttonclicked!");

});

 ◆Supportsmultipleeventbindingsforthesameelement.

 ◆Doesnotoverrideexistingeventlisteners.

2. UsingJavaScript(onclickorInlineEventHandler)

 Assigninganeventhandlerdirectlytotheonclickproperty.

Dept of ISE, RIT, Hassan Page21


BIS601|FULLSTACKDEVELOPMENT

 Syntax:

element.event=function;

 Example:

document.getElementById("btn").onclick=function(){

alert("Buttonclicked!");

};

 ⚠Limitations:

o Canonlybindoneeventatatime(overwritesprevious event).

o Notsuitablefordynamicelements.

3. UsingjQuery(.on())

 The.on(event,selector,function)methodisusedtobindevents
dynamically.

 Syntax:

$(selector).on("event",function);

 Example:

$("#btn").on("click",function()

{ alert("Button clicked!");

});

Dept of ISE, RIT, Hassan Page22


BIS601|FULLSTACKDEVELOPMENT

 ⬛Worksondynamicallyaddedelements.

 ⬛Canbindmultipleeventsatonce.

4. UsingjQuery(.click(),.hover(),etc.)

 Shortcutmethodsforspecificevents.

 Example:

js

CopyEdit

$("#btn").click(function()

{ alert("Button clicked!");

});

 ◆Simplersyntaxbutdoesnotworkfordynamicallycreatedelements.

5. BindingMultipleEventstotheSameElement

 JavaScript(addEventListener):

js

CopyEdit

letbtn =document.getElementById("btn");

btn.addEventListener("mouseover",function(){console.log("Mouseover!");});

Dept of ISE, RIT, Hassan Page23


BIS601|FULLSTACKDEVELOPMENT

btn.addEventListener("click",function(){console.log("Buttonclicked!");});

 jQuery(.on()):

js

CopyEdit

$("#btn").on("mouseoverclick",function()

{ console.log("Mouse over or clicked!");

});

6. BindingEventstoMultipleElements

 JavaScript(querySelectorAll):

js

CopyEdit

document.querySelectorAll(".buttons").forEach(button=>{ button.addEventListene

r("click", function() {

alert("Oneofthebuttons clicked!");

});

});

 jQuery(.each()):

js

Dept of ISE, RIT, Hassan Page24


BIS601|FULLSTACKDEVELOPMENT

CopyEdit

$(".buttons").each(function(){

$(this).on("click", function()

{ alert("Oneofthebuttonsclicked!");

});

});

7. BindingEventstoDynamicallyAddedElements

 JavaScript(EventDelegationusingdocument.addEventListener):

js

CopyEdit

document.addEventListener("click",function(event){

if(event.target.classList.contains("dynamic-btn")){

alert("Dynamicallyaddedbuttonclicked!");

});

 jQuery(.on()):

js

CopyEdit

Dept of ISE, RIT, Hassan Page25


BIS601|FULLSTACKDEVELOPMENT

$(document).on("click",".dynamic-btn",function()

{ alert("Dynamically added button clicked!");

});

 ⬛WorksforelementsaddedlaterviaJavaScript/jQuery.

8. RemovinganEventBinding

 JavaScript(removeEventListener):

function myFunction() {

alert("Clicked!");

document.getElementById("btn").addEventListener("click", myFunction);

document.getElementById("btn").removeEventListener("click",myFunction);

 jQuery(.off()):

$("#btn").on("click",function(){alert("Clicked!");});

$("#btn").off("click");//Removesclickevent

EventDelegationinJavaScript&jQuery Event

Delegation

Dept of ISE, RIT, Hassan Page26


BIS601|FULLSTACKDEVELOPMENT

EventdelegationisatechniqueinJavaScriptwhereasingleeventlistenerisadded to a
parent element to handle events on multiple child elements, including dynamically
added elements.

⬛Efficient–Reducesmemoryusagebyattachingfewereventlisteners.
⬛Handles Dynamic Elements – Works even when new elements are added
dynamically.
⬛Better Performance – Instead of attaching events to every element, it
delegateshandlingtoacommonparent.

HowEventDelegationWorks?

1. Addaneventlistenertoacommonparentelement.

2. Useevent.targettocheckiftheeventwastriggeredbytheintendedchild
element.

3. Executetheeventhandleronlyifthecorrectchildelementis clicked.

1. EventDelegationUsingJavaScript

Dept of ISE, RIT, Hassan Page27


BIS601|FULLSTACKDEVELOPMENT

Example:HandlingClicksonaListofItems

document.getElementById("list").addEventListener("click",function(event){ if

(event.target.tagName === "LI") {

alert("Clickedon:" +event.target.textContent);

});

◆ Theeventlistenerisattachedtothe #listparent,butitworksforall
<li> elements inside it.
◆ Worksevenfornew<li>itemsadded later.

2. EventDelegationUsingjQuery

Example:HandlingClicksonButtonsinsideaParentDiv

$(document).on("click",".child-btn",function(){ alert("Button

clicked: " + $(this).text());

});

Dept of ISE, RIT, Hassan Page28


BIS601|FULLSTACKDEVELOPMENT

◆ Theeventisattachedto document,butitlistensfor.child-btnclicks.
◆ Worksfordynamicallyadded.child-btnelements.

4. WhentoUseEventDelegation?

⬛Whendealingwithlists, tables,orelementscreated dynamically(e.g.,<ul>,


<table>,<div>)
⬛When handling repetitive UI components (e.g., buttons inside cards, form fields
inside a container)
⬛Whenoptimizingperformanceforhigh-interactionwebpages

5. WhenNottoUseEventDelegation?

ı.Ifthechildelementshavedifferenteventhandlersthatmustbeunique
ı.Ifcapturingeventbehaviorisneeded(i.e.,focus,blur,mouseenter)
ı. If immediate response is required (event delegation may have a slight delay
inlarge DOM structures)

Dept of ISE, RIT, Hassan Page29


BIS601|FULLSTACKDEVELOPMENT

6. Real-WorldExample

DynamicallyAddingandHandlingClickEvents

document.getElementById("addItem").addEventListener("click",function()

{ let newItem = document.createElement("li");

newItem.textContent = "New Item";

document.getElementById("list").appendChild(newItem);

});

// Event Delegation for Handling Clicks

document.getElementById("list").addEventListener("click",function(event){

if(event.target.tagName==="LI"){

alert("Youclickedon:"+ event.target.textContent);

});

◆ Clickingonnewlyadded<li>itemsstilltriggerstheevent!
7'•˙¸.s

EventListenersinJavaScript&jQuery

What is an Event Listener?

Aneventlistenerisafunctionthatwaitsforaspecificevent(likeaclick,hover, or
keypress) to happen on an element and executes a function in response.

Dept of ISE, RIT, Hassan Page30


BIS601|FULLSTACKDEVELOPMENT

⬛Detectsuserinteractions(clicks,keyboardinput,scrolling,etc.)
⬛Enhancesinteractivityinwebapplications
⬛ CanbeappliedtomultipleelementswithoutmodifyingHTML

1. AddingEventListenersinJavaScript

UsingaddEventListener()

TheaddEventListener()methodattachesaneventtoanelementwithout overwriting
existing events.
Syntax:

element.addEventListener("event",function,useCapture);

 "event"→Typeofevent(e.g.,"click","mouseover","keydown")

 function→Thefunctiontoexecutewhentheeventoccurs

 useCapture(optional)→trueforeventcapturing,falseforbubblin

g Example: Button Click Listener

document.getElementById("btn").addEventListener("click",

function() {

alert("ButtonClicked!");

});

⬛Supportsmultipleeventlistenersonthesameelement
⬛Moreflexiblethanonclick

Dept of ISE, RIT, Hassan Page31


BIS601|FULLSTACKDEVELOPMENT

UsingInlineEventHandlers(onclick,onmouseover)

Youcandirectlyassignaneventtoanelementusingpropertieslikeonclick.
Example:

document.getElementById("btn").onclick=function()

{ alert("Button Clicked!");

};

⚠Limitations:

 Overwritesanypreviouslyassignedeventhandlers

 Notidealforhandlingmultipleevents

UsingAnonymousvsNamedFunctions

Bothanonymousandnamedfunctionscanbeusedineventlisteners.

⬛AnonymousFunction(InlineFunction)

document.getElementById("btn").addEventListener("click",function()

{ alert("Button Clicked!");

Dept of ISE, RIT, Hassan Page32


BIS601|FULLSTACKDEVELOPMENT

});

⬛Named Function

function showAlert()

{ alert("ButtonClicked!");

document.getElementById("btn").addEventListener("click",showAlert);

Dept of ISE, RIT, Hassan Page33


BIS601|FULLSTACKDEVELOPMENT

◆ AdvantageofNamedFunction:Canbereusedandremovedeasily

2. RemovingEventListeners

Use removeEventListener() to detach an event listener.

document.getElementById("btn").removeEventListener("click",showAlert);

⚠Thefunctionmustbenamedwhenremovingit.Anonymousfunctionscannot be
removed.

3. EventListenersinjQuery

Using.on() (Recommended)

The.on()methodattachesaneventlistenerdynamically.

$("#btn").on("click",function()

{ alert("Button Clicked!");

});

⬛Worksevenfordynamicallyaddedelements
⬛Canbindmultipleevents

Using.click(),.hover(),.keypress()(ShortcutMethods)

$("#btn").click(function(){

Dept of ISE, RIT, Hassan Page34


BIS601|FULLSTACKDEVELOPMENT

alert("ButtonClicked!");

});

⚠Thesemethodsdonotworkondynamicallyaddedelements.Use.on() instead.

4. EventPropagation(Bubbling&Capturing)

EventstravelthroughtheDOMin two phases:


1️⃣ CapturingPhase(ToptoBottom)
2️⃣BubblingPhase(BottomtoTop)

Example:BubblingEffect

document.getElementById("parent").addEventListener("click",function()

{ alert("Parent Clicked!");

});

document.getElementById("child").addEventListener("click",function(event)

{ alert("Child Clicked!");

});

◆ Clickingon#childwilltriggerbothlisteners(child→parent).

StoppingEventBubbling

Useevent.stopPropagation()topreventbubbling.

Dept of ISE, RIT, Hassan Page35


BIS601|FULLSTACKDEVELOPMENT

document.getElementById("child").addEventListener("click",function(event){

event.stopPropagation();

alert("ChildClicked,butparentwon'ttrigger!");

});

5. BindingMultipleEventstoanElement

AttachmultipleeventlistenersusingaddEventListener()or.on().

JavaScriptExample

letbtn =document.getElementById("btn");

btn.addEventListener("mouseover",function(){console.log("MouseOver!");});

btn.addEventListener("click", function() { console.log("Button Clicked!"); });

jQuery Example

$("#btn").on("mouseoverclick",function()

{ console.log("Mouse Over or Clicked!");

});

6. EventDelegation

Insteadofattachinglistenerstoeachelement,attachittoaparentanduse event.target to
handle child elements dynamically.

Dept of ISE, RIT, Hassan Page36


BIS601|FULLSTACKDEVELOPMENT

JavaScriptExample

document.getElementById("parent").addEventListener("click",function(event)

{ if (event.target.tagName === "BUTTON") {

alert("Buttoninsideparentclicked!");

});

jQueryExample

$(document).on("click",".child-btn",function()

{ alert("Dynamically added button clicked!");

});

⬛Bestforhandlingdynamicallygeneratedelements.

7. CommonEventListenerTypes

Dept of ISE, RIT, Hassan Page37


BIS601|FULLSTACKDEVELOPMENT

Dept of ISE, RIT, Hassan Page38

You might also like