15

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

spiderman
  • 1,397
  • 2
  • 10
  • 18
  • 1
    It's `document`, not `"document"`, you have syntax error (missing `});`), and if you want to prevent link from taking you to a page use `e.preventDefault()` – Esailija Jan 21 '12 at 10:15

5 Answers5

26

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:

bud-e
  • 1,511
  • 1
  • 20
  • 31
Krzysztof Bujniewicz
  • 2,407
  • 21
  • 16
3

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

dknaack
  • 60,192
  • 27
  • 155
  • 202
  • 1
    Generally it is not a good idea to `return false;` when you only want to prevent the default action; it will interfere with other event handlers. Also, you can only use it on the end of the function, so if there is any javascript error, the browser will still follow the link, which might be unwanted. As Esailija said, `e.preventDefault()` is the better solution. – Tgr Jan 21 '12 at 10:20
0

try this

$(document).ready(function(){
    $('.alink .p').click(function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        alert("hi");
        return false;
    });
});
Dau
  • 8,578
  • 4
  • 23
  • 48
0

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

Vivek
  • 10,978
  • 14
  • 48
  • 66
0

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.

gregolsen
  • 925
  • 9
  • 12