If I'm not returning false
from an event callback, or using e.stopPropagation
feature of jQuery, the event bubbles up the DOM.
In most scenarios I don't care if the event bubbles or not. Like with this DOM structure example:
<div id="theDiv">
<form id="theForm" >
<input type="submit" value="submit"/>
</form>
</div>
Normally, I don't have multiple nested submit callback like this:
$('#theDiv').submit(function() {
alert('DIV!');
});
$('#theForm').submit(function(e) {
alert('FORM!');
e.preventDefault();
});
Fiddle
That DEMO shows the submit
event bubbles to a <div>
!
It has no difference to me if I stop the Propagation or just prevent default.
In those scenarios, If I stop the propagation will I gain performance benefits?
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object (Provided the handler is initialized).
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.
preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.
Performance benefits? Yes, there are some slight benefits, as outlined in this performance test between jQuery live()
and on()
. As @Joseph also noted, the difference between the two is that live propagates all the way up the tree, while on()
only goes to the nearest common parent.
In those tests, it is shown that on()
can outperform live()
by up to 4 times. In practice, that's probably still not worth splitting hairs over, but if you have very deep html structures and lots of event triggers, the performance difference in stopping propagation can be worthwhile, I suppose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With