Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop redirection of parent href tag when clicked on child div?

i have the following structure

Code

 <a href="blah.html" class="re-direct">
    <div class="1div"></div>
    <div class="2div">
       <div class="click" data-id="text">click</div>
    </div>
 </a>
 <script>
  $(document).on('click',".click",function(){ alert($(this).data('id')) })
 </script>

the above code works fine but it redirects to the page blah.html how do i stop it from redirecting ?

like image 260
Dev Man Avatar asked Jul 13 '14 19:07

Dev Man


1 Answers

You need to stop the propagation of the click event up the DOM to the a element, and also prevent the default behaviour of the link:

$(document).on('click', ".click", function(e) {
  e.stopPropagation();
  e.preventDefault();
  console.log($(this).data('id'))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<a href="blah.html" class="re-direct">
  <div class="1div"></div>
  <div class="2div">
    <div class="click" data-id="text">click</div>
  </div>
</a>
like image 160
Rory McCrossan Avatar answered Oct 04 '22 20:10

Rory McCrossan