JQuery event efficiency: bind one event to parent or separate events for each child?
I have a div with a huge number of child divs (about 4k-5k!). Each child has an event attached to it 'mousedown'
and 'mouseup'
.
Should I instead attach these events to the parent and select the child with $(e.target)
? Would there be some kind of performance advantage, and if so why?
Thank!
source to share
I would imagine using jquery.on () would be ideal.
$("#divWithHugeAmountsOfChildDiv").on("mousedown",
".childCLASSEStoMouseDown",
function()
{
alert("Booya!");
});
Where your html might look like:
<body>
<!-- lots of other elements -->
<div id="divWithHugeAmountsOfChildDiv">
<!-- lots of different type of elements -->
<div class="childCLASSEStoMouseDown">Booya?</div>
<!-- lots of different type of elements -->
</div>
<!-- lots of other elements -->
</body>
Changing jQuery selectors as needed ...
Why this is very well explained in the jQuery documentation for the method On
.
source to share
using jQuery .on()
already does this for you. It associates an event handler with a specific parent and detects child events. It has performance advantages .live()
and .bind()
as well as direct event binding, for example .click()
, etc., because:
-
as opposed to
.live()
which one binds the event todocument
, with using.on()
you are responsible for which parent object is bound. -
.live()
is bound todocument
, which is the document root. the events that bubble up will move on. using.on()
you can find the closest common parent to bind this event. the bubble will move less - performance advantage -
c
.on()
, you only bind one handler to the parent, unlike.bind()
and direct event bindings, which bind events on a per element basis - not suitable for a large number of elements. -
.on()
easier to remember. -
when the target is reached inside
.on()
"this" is always the target element. never worry about cross-browser targets. jQuery does this for you.
so "this" in this code:
$(element).on('click','someElement',function(){
//the value of "this" in here is the DOM element target of the event
});
source to share
With this many child divs, you should definitely use jQuery delegated event handling .on()
. This will give you one parent event handler instead of 4000 child event handlers. It will also be much faster to install and initialize.
If you are using a delegated form .on()
, you won't need to validate e.target
yourself as jQuery will do it for you.
The syntax to use .on()
this way is as follows:
$('parentSelector').on('mousedown', 'child selector', function(e) {
// code here
// "this" will be the object that initiated the event
});
More information in the jQuery doc for.on()
.
source to share