Reputation: 1417
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
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
Reputation: 60486
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"
.
$(document).ready(function(){
$('.alink, .alink > .p').click(function(e){
e.preventDefault();
e.stopPropagation();
alert("hi");
});
});
Upvotes: 3
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
Reputation: 11028
you should use- e.preventDefault()
to stop default behavior. stopPropagation is used to stop event bubbling.
Upvotes: 0
Reputation: 8858
try this
$(document).ready(function(){
$('.alink .p').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
alert("hi");
return false;
});
});
Upvotes: 0