How can I stop the propagation of the click event so that the browser will NOT redirect?
<a id="theHref" href="/">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>
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>
Share
Improve this question
edited May 14, 2021 at 15:16
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Jun 28, 2015 at 9:35
nagy.zsolt.hunnagy.zsolt.hun
6,69416 gold badges64 silver badges102 bronze badges
4 Answers
Reset to default 13Firstly, 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
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
This should work:
document.getElementById("theHref").addEventListener("click", function(event) {
console.log("href clicked, lets try to stop event propagation");
event.preventDefault();
});
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.