How to cancel navigation when user clicks a link ( element)?

If you have HTML like this:

<a href="https://stackoverflow.com/questions/866583/no_javascript.html" id="mylink">Do Something</a>

You would do something like this with jQuery:

$(document).ready(function() {
    $('#mylink').click(function() {
        doSomethingCool();
        return false; // cancel the event
    });
});

All you have to do is cancel the click event with Javascript to prevent the default action from happening. So when someone clicks the link with Javascript enabled, doSomethingCool(); is called and the click event is cancelled (thus the return false;) and prevents the browser from going to the page specified. If they have Javascript disabled, however, it would take them to no_javascript.html directly.

Leave a Comment