Reputation: 7734
I have a piece of HTML like:
<a href="http://site.com">
<span id="a">Click here to link to site.com</span>
<span id="b">Click here not to link to site.com</span>
</a>
Without changing the DOM structure, just by JavaScript, how can I prevent span#b
from linking to site.com when it's clicked?
I use jQuery in this project so it's better to implement with jQuery.
Thanks,
update:
Sorry I found the answers that return false
or .stopPropagation()
not working in a particular situation. So I have uploaded more details:
This is the DOM tree, sorry I have to hide some personal information:
Here is the related code:
$('.span_wrapper').click(function(e){
e.stopPropagation();
alert('clicked');
return false;
});
It still links to the page to href value of the outside <a>
tag.
Update: here is a video explaining what I was trying:
https://www.facebook.com/photo.php?v=10201864154343615
Upvotes: 0
Views: 77
Reputation: 38345
Just prevent the event from propagating/bubbling up from the #b
element to the <a>
element:
$('#b').on('click', function(e) {
e.preventDefault();
// any other code to react to this click here
});
There's also a shorthand version to achieve the same thing (if you don't have any other logic):
$('#b').on('click', false);
From the docs:
The value
false
is also allowed as a shorthand for a function that simply doesreturn false
.
Calling return false
from the jQuery event handler is the equivalent of calling both event.stopPropagation()
and event.preventDefault()
. The advantage to calling e.preventDefault()
at the beginning of the function is that it will still prevent the link from being followed even if there are errors thrown executing the rest of the handler function.
NOTE: As always when working with elements you need to ensure they actually exist before attempting to do so. That either means a DOM ready handler or moving the script to the end of the HTML document, just before the </body>
tag.
Upvotes: 6
Reputation: 2983
something like this would work i think
$("a #b").click(function(){return false});
Upvotes: 1
Reputation: 11302
Stop propagation binding a click
event to span#b
$('#b').click(function(e) {
e.stopPropagation();
return false;
});
Upvotes: 0