Neil
Neil

Reputation: 5188

Other ways to stop bubbling from inner event handlers, jQuery

Example Code shown here. This works, but I am wondering if there is another way to do this without having to create an event handler for the sole purpose of preventing bubbling up messages performed on it, up to its ancestors.

Basically what I want the code to do is this: Everywhere that the span tag is not, then call the event handler for the p tag. Another way of wording it: Everywhere that the span tag is, then do not call the event handler for the p tag.

I attempted to do this, but it didn't work. When clicking on the span tag it still bubbles up, which is what I want to prevent

Upvotes: 2

Views: 54

Answers (2)

Travis J
Travis J

Reputation: 82357

jsFiddle Demo

Check the event target for the mouse event. If the target is a span, then return out of the handler

$("div").on('click', "p", function(e){
 if($(e.target).is("span"))return;
 alert("p was clicked"); 
});

Upvotes: 2

Leah Zorychta
Leah Zorychta

Reputation: 13459

jsFiddle demo

$("div").on('click', "p", function(e){
    if(e.target.nodeName != 'SPAN') {
      alert("p was clicked"); 
    }
});

check the type of the element clicked in your first event handler. Only show the alert when it's a P element.

edit: more information on the parameter that jQuery passes to an event handler: e.currentTarget refers to the element you've placed an event listener on (in this case your p tag) and e.target refers to the element that you've actually clicked (which refers to the span element when you click on the span, and the p element when you click on the p).

Upvotes: 3

Related Questions