spiderman
spiderman

Reputation: 1417

does e.stopPropagation() in jquery works on anchor tag

i want prevent eventpropogation from element inside an anchor tag i m trying to use e.stopPropagation(); it doesn't seem to work is it possible or i m just wasting time please help me out of here javascript is:

$(document).ready(function(){
    $('.alink .p').click(function(e){
    alert("hi");
    e.stopPropagation();  
});

html is :

<div>
    <a href="http://google.com" class="alink" >Google links
          <p class="p">Another Links to prevent default</p>
    </a>
</div>

thanks for your precious time

Upvotes: 15

Views: 12160

Answers (5)

Krzysztof Bujniewicz
Krzysztof Bujniewicz

Reputation: 2417

event.stopPropagation() stops passing the event to handlers further away in DOM structure from the element, on which originally event was triggered. It does not, although, prevent action that has already been triggered.

You should use event.preventDefault() to stop mentioned above default action.

Sources:

Upvotes: 26

dknaack
dknaack

Reputation: 60486

Description

It will not stop any default behaviours (such as link clicks) and you might want to consider using event.preventDefault() in addition to this method.

event.stopPropagation() is only for event handlers, not default behavior.

event.preventDefault() If this method is called, the default action of the event will not be triggered.

You had some spelling errors in your script and its document not "document".

Check out the Sample and this jsFiddle Demonstration

Sample

$(document).ready(function(){
    $('.alink, .alink > .p').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        alert("hi");
    });
});

More Information

Upvotes: 3

gregolsen
gregolsen

Reputation: 915

You've missed enclosing brackets here, didn't you?

$('document').ready(function(){
    $('.alink .p').click(function(e){
    alert("hi");
    e.stopPropagation();  
});

Fix brackets and then use e.preventDefault() instead.

Upvotes: 0

Vivek
Vivek

Reputation: 11028

you should use- e.preventDefault() to stop default behavior. stopPropagation is used to stop event bubbling.

Upvotes: 0

Dau
Dau

Reputation: 8858

try this

$(document).ready(function(){
    $('.alink .p').click(function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        alert("hi");
        return false;
    });
});

Upvotes: 0

Related Questions