3

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

Community
  • 1
  • 1
Vucko
  • 20,555
  • 10
  • 56
  • 107

6 Answers6

7

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>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
3

Try:

e.preventDefault();

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

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
  • 2
    stopPropagation stops events from bubbling up, in this case you still clicked on the link since it wraps the span so you need to stop the browser from doing its default action. – AtheistP3ace Oct 21 '15 at 14:57
1

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();
});
javifm
  • 705
  • 4
  • 9
  • 20
0

Try to use e.preventDefault() instead:

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

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

Community
  • 1
  • 1
Ron C
  • 1,176
  • 9
  • 12
0

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.

Alex
  • 9,911
  • 5
  • 33
  • 52
0

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
}
Giddy Naya
  • 4,237
  • 2
  • 17
  • 30