Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering a custom jQuery event without bubbling

Tags:

jquery

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?

like image 504
Arun Avatar asked Jun 03 '13 12:06

Arun


People also ask

How do I stop jquery from bubbling?

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.

Which method prevent the event from bubbling up the DOM tree?

stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

What does event stopPropagation () do?

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.


1 Answers

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.

like image 184
Frédéric Hamidi Avatar answered Nov 15 '22 23:11

Frédéric Hamidi