Vucko
Vucko

Reputation: 20834

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).

Upvotes: 4

Views: 10347

Answers (6)

Giddy Naya
Giddy Naya

Reputation: 4658

I know this question already has an answer but however, I made mine work by returning false on the "onclick" attribute of the child element.

<a href="https://google.com">
    <button onclick="return doTask()">Do not navigate</button>
</a>

function doTask(){
  //... write action

  return false; <- This prevents the click action from bubbling up to parent tag
}

Upvotes: 0

Ron C
Ron C

Reputation: 1206

Try to use e.preventDefault() instead:

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

See this explanation for why e.stopPropagation() is not working.

Upvotes: 0

Alex
Alex

Reputation: 10216

use return false:

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

    //some logic
    $(this).css('color', 'red');

    return false;
});

The reason why stopPropagation wont work is because it will prevent event handlers from running, not native behavior.

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

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>

Upvotes: 7

javifm
javifm

Reputation: 705

You should use e.preventDefault(); on links:

$('#bar').on('click', function(e) {
    e.preventDefault();
});

You can also add it on your example, all together:

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

Upvotes: 1

AtheistP3ace
AtheistP3ace

Reputation: 9691

Try:

e.preventDefault();

Fiddle: http://jsfiddle.net/hfyy10a8/3/

Upvotes: 3

Related Questions