Skip to content
Advertisement

Prevent redirect when clicking on anchors child element

I have a button that’s located in an anchor, and that button has some logic that’s triggerd by clicking on it.

The problem is that whenever I click on that button, the app get’s redirected due the anchor parent element.

<a href="foo" id="bar">
  <span id="button">click me</span>
</a>

I tried using .stopPropagation() like it’s mentioned in this post, however it doesn’t work.

I tried:

$('#button').on('click', function(e) {
    e.stopPropagation();
})

Here’s the fiddle.

However, if I replace the parent anchor with a div, then it works – JSFiddle

Am I doing something wrong?

Update: I know I can prevent redirecting with e.preventDefault(), however, I want when I click on the parent element to redirect, and when I click on the button not to redirect and start doing my JS functions (open modal).

Advertisement

Answer

Try this:

$('#bar').on('click', function(e) {
    if( $(e.target).is('#button') ) {
        e.preventDefault();
        //your logic for the button comes here
    }
    //Everything else within the ancho will cause redirection***
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="foo" id="bar">OK
  <span id="button">click me</span>
</a>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement