Volodymyr
Volodymyr

Reputation: 1587

Bind an event to some element without binding to it's child - JQuery

I have some div called mydiv. I have a click event attached to it. Inside of the div I have a link. I want the event not to be triggered after clicking on the link. Smth like

$(document).on('click', '#mydiv a', function(){
    // How to disable parent's event here?
});

Thank you!

Upvotes: 2

Views: 2404

Answers (3)

billyonecan
billyonecan

Reputation: 20250

The problem you have is that the click handler bound to the div will trigger first because the delegated event will only fire once the event has propagated right up to the document.

In your #mydiv click handler, check that the event.target === this before executing any code, that way, it'll only fire when the div has been clicked.

Something like this:

$('#mydiv').on('click', function(e) {
    if (e.target === this) {
      alert('div click fired!'); 
    }
});

$(document).on('click', '#mydiv a', function(e) {
   alert('anchor click fired!'); 
});

Here's a fiddle


Edit If the only reason you're attaching an event handler to the anchor is to prevent triggering the click handler on the div, just check if the target is not an anchor in the div click handler before doing anything else:

$('#mydiv').on('click', function(e) {
    if ($(e.target).is('a')) {
        return;
    }
    alert('div click fired!'); 
});

Here's another fiddle

Upvotes: 3

David MacCrimmon
David MacCrimmon

Reputation: 966

This should do what you're looking for:

$(document).on('click', '#mydiv a', function(e){
    // How to disable parent's event here?
    e.stopPropagation();
});

Upvotes: 2

Coder
Coder

Reputation: 7076

Try this so you can use single JQuery

HTML

<div id="mydiv">
    <span> Hello, How are you? </span>
    <a id="alink" href="#"> Click ME </a>
</div>

JQUERY

$(document).on('click', '#mydiv', function(event){
   alert("You clicked on Div Span");
 }).children().find("#alink").click(function(e) {
  return false;
});

JSFiddle Demo

Upvotes: 0

Related Questions