Jquery 'On' (Events,Direct ,Delegated)

jQuery makes it easy to respond to user interaction with a web page. Example, this code listen to click event on all element in a document and alert the text in it.

HTML
click 1
click 2
JQUERY

There are other methods for event binding such as click(), keydown(), keyup(), blur() and so on, all of which make use of jQuery's .on() method.
jQuery's .on() method attachs an event handler function for one or more events on selected elements.


The example given above is Direct event. which basically means :
HEY!!!! I want every div to listen up: when you get clicked , give me alert.

Here, each of these div has been individually given click event which works as it should.

However  if you notice in jquery's DOC,
According to the jquery's documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

so, now what if some of the div is generated dynamically.For example.

Looking at the code, the newly appended div should give us an alert when clicked, since we already have a click event binding to all div element (selector as $('div')). But this won't.

Try this in FIDDLE

So why isn't the click event firing here!!!
this is because event handlers are bound only to the currently selected elements, they must exist on the page at the time your code makes the call to .on() .

Now what should be done???
well, no worries, This is where the on DELEGATE events comes into play.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.


Hey,  document!!!! When any of your child elements which is "div" get clicked, give us an alert and append another div.

Here, only the document has been given the instruction, it is responsible for noticing clicks on behalf of its child div. The work of catching events has been delegated.

Hoooollaaa!!!!! this works....
Try this in FIDDLE

It is preferred to delegate events with the closest static elements then the document for better performance.For example
HTML
click 1
click 2
JQUERY

Try this in FIDDLE

Comments

Post a Comment

Popular posts from this blog

jquery attr() vs prop() (difference)

PHP Profiling Using Xdebug and Kcachegrind