AGamePlayer
AGamePlayer

Reputation: 7734

How do I prevent the clicks on specified element(s) inside a <a> tag not linking out?

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:

DOM Tree

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

Answers (3)

Anthony Grist
Anthony Grist

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 does return 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

Richard Banks
Richard Banks

Reputation: 2983

something like this would work i think

$("a #b").click(function(){return false});

Upvotes: 1

letiagoalves
letiagoalves

Reputation: 11302

Stop propagation binding a clickevent to span#b

$('#b').click(function(e) {
   e.stopPropagation();
   return false;
});

Upvotes: 0

Related Questions