Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent default link behavior if element inside of link is clicked

I have a link that looks like this:

<a href="page.html" class="myLink">
  Link text
  <div class="toggle">x</div>
</a>

When they click on the x in toggle I want to prevent the link from navigating, but if they do click on the Link Text I want the link to navigate.

I tried this:

$('.toggle').click(function(event) { $(this).parents('a').preventDefault(); });

But it didn't seem to work.

like image 507
Talon Avatar asked Sep 06 '25 03:09

Talon


1 Answers

To stop propagation from the clicked element to the outer a, you'd have to call stopPropagation. But here you can simply return false ( which both stops propagation and prevents default behavior) :

$('.toggle').click(function(event) {
    // do interesting things   
    return false
});
like image 51
Denys Séguret Avatar answered Sep 07 '25 20:09

Denys Séguret