0

I want to stop the parent event to fire up when I click the child link. here it is my code:

$('.list_row_inputtype').on('click',function(event) {

    $(this).find('a.link_to_fire').click();
    event.stopPropagation();
  
    return false;
});


<div class="list_row_input_type unread"> 
    <a href="#" onclick="toogleRead(); return false;" class="toogleRead"></a>
    <a href="{corePath}/mails" class="link_to_fire">{emailLink}</a>
    <div class="description"></div>
</div>

When I click on .toogleRead it fire the function, but change to the {corePath}/mails page too. I want to prevent it to change the page.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1

You should add the event handler on the .toogleRead element via jQuery too. It's easier to remember where handler are attached, it doesn't mix two ways of doing, and add a better separation between HTML and Javascript.

Here is a working demo http://jsfiddle.net/pomeh/uFV9R/.

HTML code

<div class="list_row_input_type unread"> 
    <a href="#" class="toogleRead"></a>
    <a href="{corePath}/mails" class="link_to_fire">{emailLink}</a>
    <div class="description"></div>
</div>

Javascript code

$('.list_row_input_type').on('click',function(event) {
    event.stopPropagation();
    // your stuff
});

$('a.toogleRead').on('click',function(event) {
    event.stopPropagation();
});

Another point, returning false from an event handler with jQuery is, in most cases, considered a bad practice. It does too many things where you usually only want to do one of them. Here is two links that explain this in detail http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ and http://css-tricks.com/return-false-and-prevent-default/.

pomeh
  • 4,742
  • 4
  • 23
  • 44
0

Can you place the clent event on the a instead? Now you wouldn't have to worry about the event propagation.

$('.list_row_input_type.unread a.toggleRead').click(function(e) {
  e.preventDefault();
  toggleRead();
});
lucuma
  • 18,247
  • 4
  • 66
  • 91