Last Updated: February 25, 2016
·
396
· gilesa

Reduce event handlers by using the parent element.

When you want to handle the same event on a large number of related dom elements, you can reduce overhead by attaching a single event handler to their parent element, instead of attaching a new one on each element. Do so by using the .on method on the parent element and specifying a selector for the actual elements you want to handle the event for.

For example, say you wanted to handle click events on each a element:

<div id="mydiv">
    <a href="#">We</a>
    <a href="#">Care</a>
    <a href="#">About</a>
    <a href="#">Only</a>
    <a href="#'>These</a>
    <h1>Other stuff</h1>
    <p>Will get ignored</p>
</divl>

Instead of:
$('#mydiv a').on( 'click', function( event ) { ... } );

Do:
$('#mydiv').on( 'click', 'a', function( event ) { ... } );

This will attach a single click event handler to #mydiv, but it will only execute when a click event occurs on a a element.

See the jquery docs for more details.