06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

DOM Manipulation and Events<br />

You can add multiple event handlers for multiple events as follows:<br />

$( "#heading" ).on({<br />

mouseenter: function() {<br />

console.log( "mouse entered on heading" );<br />

},<br />

mouseleave: function() {<br />

console.log( "mouse left heading" );<br />

},<br />

click: function() {<br />

console.log( "clicked on heading" );<br />

}<br />

});<br />

As of jQuery 1.7, all events are bound via the on() method, even if you call helper<br />

methods such as click(). Internally, jQuery maps these calls to the on() method.<br />

Due to this, it's generally recommended to use the on() method for consistency and<br />

faster execution.<br />

Event delegation<br />

Event delegation allows us to attach a single event listener to a parent element. This<br />

event will fire for all the descendants matching a selector even if these descendants<br />

will be created in the future (after the listener was bound to the element).<br />

We discussed event bubbling earlier. Event delegation in jQuery works primarily<br />

due to event bubbling. Whenever an event occurs on a page, the event bubbles up<br />

from the element that it originated from, up to its parent, then up to the parent's<br />

parent, and so on, until it reaches the root element (window). Consider the following<br />

example:<br />

<br />

<br />

<br />

<br />

Google<br />

Myntra<br />

Bing<br />

<br />

<br />

<br />

<br />

[ 198 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!