Search code examples
javascriptdom-eventshref

Stop propagation of click event on href


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>

Solution

  • 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