Paul
Paul

Reputation: 11746

stopPropagation not working with nested href tag

I have multiple divs listed like so:

<div class="msg-list clearfix" id="27705">
  <div class="thumbnail_image">
    <a href="some_path">AnchorText</a>
  </div>
  <div class="msg-date">DATA</div>
</div>

I've trying to catch a click event for the parent div but when clicking the href element my click event is also getting triggered instead of just following the link clicked.

Here is my jquery call:

//$(".msg-list a").click(function(e) {
$(".msg-list").click(function(e) {

    e.stopPropagation(); 
    alert("Handler for .click() called.");
});

Any idea what I'm missing?

Upvotes: 1

Views: 2263

Answers (4)

Supun Kavinda
Supun Kavinda

Reputation: 1483

Old question. But, I had the same problem.

Adding e.preventDefault() fixed the problem. The default is to follow the link. So, preventing it from following.

Also, there's no problem adding that to the <a> of its children.

Upvotes: 0

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21884

Try:

$(".msg-list").on('click', function(e) {
    alert("div handler");
    return false;
});
$(".msg-list a").on('click', function(e) {
    alert("a handler");
    e.stopPropagation();
});

Is this what you want? http://jsfiddle.net/L5kC4/2

Upvotes: 1

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

To enable the link inside the div, use this JavaScript. You have to disable Propagation on the contained element, the link!

$(".msg-list a").click(function(e) {
    e.stopPropagation();
});
$(".msg-list").on('click', function(e) {
    alert("Handler for .click() called.");
});

Upvotes: 0

Mangiucugna
Mangiucugna

Reputation: 1762

The click event, like any other event is dispatched to the elements using Bubbling (http://en.wikipedia.org/wiki/DOM_events) so any inner element clicked will trigger all the parent elements (the other way is called Tunnelling).

You have to put the stopPropagation on the anchor element onclick event or put in the element:

onclick="return false;"

Upvotes: 0

Related Questions