Quantcast
Viewing all articles
Browse latest Browse all 32

Javascript Event Delegation Model

Image may be NSFW.
Clik here to view.
javascriptlogo

JavaScript is the main part of web development. Even you can optimize the performance of java script in the web for higher efficiency.  Javascript Event Delegation Model model can be implemented for avoiding events to occur recursively through out the HTML Element.

Image may be NSFW.
Clik here to view.

The best example for event delegation is if you are creating HTML element dynamically with java-script we can easily implement event delegation model.
For Eg:- JavaScript :
// creating 10 div element inside a div without event delegation

function drawDivs(){
var adiv = document.getElementById('ID of Div'); /* parent div element ofr 10 div's */
for(1=0;i<10;i++){
var ed = document.createElement('div');
ed.setAttribute('id',i+'id');
ed.onclikc = doClick; /* creating events for all div's (recursive events)*/
adiv.appendChild(ed); /* appending to parent div */
}
}
function doClick(){
this.style.background = 'red';
}

drawDivs();

// creating 10 div element inside a div with event delegation

var adiv = document.getElementById('ID of Div'); /* parent div element ofr 10 div's */
function drawDivs(){

for(1=0;i<10;i++){
var ed = document.createElement('div');
ed.setAttribute('id',i+'id');
adiv.appendChild(ed); /* appending to parent div */
}
}

adiv.onclick = function(e){
var event = e || window.event; /* for all browsers */
var t = event.target || event.srcElement; /* for all browsers */
doClick(t);
}

function doClick(t){
t.style.background = 'red';
}

drawDivs();

The post Javascript Event Delegation Model appeared first on Mydons.


Viewing all articles
Browse latest Browse all 32

Trending Articles