views:

39

answers:

2

Let's say we have this markup:

<span href="">Text <a href="">Link</a></span>

We have events bound to both elements. How do I make it such that when I click on the anchor tag, the event on the parent will not be triggered? I've tried using the Jquery method stopPropagation() but still no luck. Any thoughts? Thanks.

+2  A: 

How are you using stopPropagation()? Something like this should work:

$("a.something").click(function(event){
  event.stopPropagation();
  window.location.href = '/your/destionation.html';
}); 
Ken Redler
+2  A: 

Not sure why stopPropagation() isn't working for you. Given your HTML example, the following code functions properly, as the event on the span is not fired.

$('span').click(function() {
    alert('span');
});

$('a').click(function(e) {
    e.stopPropagation();
    alert('a');
});

If you're using live() to bind your event handlers, then you'll have issues.

patrick dw
I have a feeling stopPropagation() not e.stopPropagation() was being used..
Dan Heberden
I tried using it the same way, and maybe I should tried again. BTW, there's an "e.preventDefault()" line, I'm not sure if this has something to do with the problem, well does it? Thanks.
HealthWarning
@HealthWarning - Are you using `live()` to bind the events? `e.preventDefault()` disables the default behavior of the element. For example, if you didn't want to follow the `href` in the `a` element, you would use it to disable the behavior of the `a`.
patrick dw