mko
mko

Reputation: 22044

How to prevent the event handler in a nested element within the target element in jQuery?

<tr>
  <td>
    <a></a>
  </td>
</tr>

Ok the thing is that the <tr> node have the event listener $('tr').click(handler1). But I don't want the <a> node have the same behaviour as the has.

Is there anyway I can do it without jQuery?

Upvotes: 1

Views: 627

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388316

You can look at something like this as an alternate to using jQuery

document.getElementById('x').addEventListener('click', function(e){
    if(e.target.tagName == 'A'){
        alert('Clicked A')
    }else{
        alert('clicked tr')
    }
    }, false);

Demo: fiddle

With jQuery:

$('tr').on('click', function(e){
    if($(e.target).is('a')){
        alert('clicked a')
    } else {
        alert('clicked tr')
    }
})

Demo: Fiddle

Upvotes: 2

coolguy
coolguy

Reputation: 7954

$('tr').click(function(e){    
     if($(e.target).is('#youranchorelementid')){ //you can use class also if you have many elements
    e.preventDefault();
    }

});

Upvotes: 1

AlexC
AlexC

Reputation: 9661

$('tr').click(function(e){
    e.preventDefault();
});

Upvotes: 1

Josh
Josh

Reputation: 3284

add a event handler to the a as well and prevent default

$(function(){
  $("tr a").click(function(e){
       e.preventDefault();
   });
});

Update:

batter yet if you want the link to continue doing the default action but you don't want the event to bubble up to the tr change it to e.stopPropagation(); instead of e.preventDefault();

Upvotes: 2

Related Questions