Tag Archives: events

jQuery live() vs bind() performance

1. What is event delegation in JavaScript?

To start with some example let’s assume that there is one DIV element with 100 A tags inside. If you assign event to every A tag that as you may know slowes down your browser. That’s a problem because sometimes that can happen, even with more than one hundred A tags. Imagine you’ve a map with one thousand markers, which are A tags. Attaching events slowes down the browser, because every of these A tags bubbles the event that has been fired. And that makes your CPU to make thousands of calculations. Of course you can avoid this problem with a simple technique. Just attach one single event on the container DIV element. Thus you can check if some child of the DIV element has been the target of the event. This makes the browser to breath. Continue reading jQuery live() vs bind() performance

cancel bubbling on element click with jQuery

When you click over an element

This is easy, on the element can be attached event listener an such event listener is built in as the click event is. It’s simply like that:

<div click="func1()"></div>

This with jQuery

A bit different with jQuery, but with the same effect is:

$('div').click(func1);

When there is a bubbling?

Well, if you just copy paste this code in your page:

$(document).click(function() 
    console.log('clicked on the document');
});
$('div').click(function() 
    console.log('clicked on the div');
});

Note: if you’re using Firefox keep the console.log function, in other case you may replace it with either alert or $.log from the recent jQuery plugin i wrote.

Now if you click over the div element you get both messages, cause there is no bubble canceling. If you’d like to add such canceling, just add this code to the click callback for the div element:

return false;

and now the code should look like:

$(document).click(function() 
    $.log('clicked on the document'); 
});
$('div').click(function() 
    $.log('clicked on the div'); return false;
});