2

I have a very basic HTML layout as follows;

    <div class="module">
        <div class="module-header">
            <h2>Heading</h2>
            <a title="a" href="/" class="btn">Link</a>
        </div>
        <div class="module-body">
            <p>Boy content here.</p>
        </div>
    </div>

I have some jQuery that toggles the module-body div when a user clicks in the module-header div as follows:

$('body').on("click", '.module-header', function(event) { 
    $('.module-body', $(this).parent()).slideToggle(300);       
});

The problem I have is that when a user clicks on the link within module-header, the toggle animation runs for a fraction of a second before the link fires. Is there a selector, or another method I can use so that the onClick event doesn't fire if the user clicks the link?

  • 1
    Check out http://api.jquery.com/event.preventDefault/ – Matthew Aug 20 '12 at 13:48
  • possible duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) -- already the second question within a couple of minutes regarding this problem. – Felix Kling Aug 20 '12 at 13:55

1 Answers1

6

Based on your last paragraph, I think you have a link in your header, which you want to allow the user to click without having the module-header's click handling cause the module-body to toggle.

To allow this, you need to intercept the event at the point where the <a> is clicked, and use stopPropagation:

$('body').on("click", '.module-header a', function (event) { 
  event.stopPropagation();
  return true;
});

This will allow your link to be clicked without the event bubbling up to the module-header's click handler. Quirks Mode has a useful article.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • If the OP is using even delegation because `.module-header` does not exist yet, this won't work. But there is not enough information to decide this. You can always inspect `event.target` I suppose. – Felix Kling Aug 20 '12 at 13:58
  • I did not expect it to work, because of the nature of event delegation. But apparently jQuery takes care of it. I don't like, because it hides what is really going on, but that's not your fault ;) – Felix Kling Aug 20 '12 at 14:11