I want to trigger a non-bubblable custom jQuery event on an object. I know we can either use return false or stopPropagation to prevent bubbling. What I want to know is can I trigger a custom event and specify that by default it does not bubble.
This is the code I have now
$(".abc").on("change", function () {
var e = new $.Event("datachange");
$(this).trigger(e)
});
The above triggers the datachange event on #abc and bubbles the event all the way up. I don't want that. I can achieve that by using the following.
$(".abc").on("change", function () {
var e = new $.Event("datachange");
//e.stopPropagation(); this does not work
$(this).trigger(e)
}).on("datachange", function (e) {
e.stopPropagation();
return false;
});
I read that triggerHandler does something similar, but only for the first matching element.
Is there a better way to achieve this?
stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.
stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.
You are right that triggerHandler() only applies to the first element in the set, but that should not be a problem because the set you build with $(this)
only contains one element.
Therefore, you can safely write:
$(".abc").on("change", function() {
$(this).triggerHandler("datachange");
});
That way, the datachange
event will not bubble up the document tree.
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