Stop propagation of click event on href
Asked Answered
M

4

6

How can I stop the propagation of the click event so that the browser will NOT redirect?

<a id="theHref" href="http://stackoverflow.com/">SO</a>
<script>
    document.getElementById("theHref").addEventListener("mousedown", function(event) {
        console.log("href clicked, lets try to stop event propagation");
        event.stopPropagation();
        event.preventDefault();
        return false;
    });
</script>
Mages answered 28/6, 2015 at 9:35 Comment(0)
D
13

Firstly, you want to listen on the "click" event, not mousedown

document.getElementById("theHref").addEventListener("click", function(event) {
    console.log("href clicked, lets try to stop event propagation");
    event.preventDefault();
    return false;
});

not sure you need the return false - I can never remember cross browser nuances like that :p return false does NOT stop Firefox, for instance

Dallis answered 28/6, 2015 at 9:37 Comment(3)
thanks for the answer, but it doesn't work (tried in FF and in Chrome). I've updated my question with your recommendationMages
You're still listening to "mousedown", rather than "click"Dallis
You are right. Listening to "click" solves my problem. Thanks.Mages
W
0

Just try by using return false that is the simple method which will not make you redirect

<script>
$(function(){   
$("#theHref").click(function(){
  return false;
});
});
</script>

Just refer this fiddle Fiddle

Wirephoto answered 28/6, 2015 at 9:39 Comment(1)
jQuery return false in event handlers is the same as event.stopPropagation and event.preventDefaultMages
D
0

This should work:

document.getElementById("theHref").addEventListener("click", function(event) {
    console.log("href clicked, lets try to stop event propagation");
    event.preventDefault();
});
Dredge answered 28/6, 2015 at 10:23 Comment(0)
B
0

Try this.

<a href="https://www.google.com/" onclick="event.stopPropagation()">Click Here</a>

there is a default event object available on elements. You can access it to disable/stop the event propagation.

Bandurria answered 30/4, 2024 at 7:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.