Disable a link from going to the href URL with jQuery

Posted in Javascript -

When assigning a click handler to an anchor tag with jQuery you'll often want to then prevent the browser from clicking through to the actual link. There are two ways I know of to do this with jQuery and these are presented there.

Example that doesn't stop the default action

All jQuery code examples below use the following HTML link:

<a id="exampleLink" href="https://www.electrictoolbox.com/">Chris Hope's LAMP Blog</a>

The first example below assigns a handler so when the user clicks the link it displays an alert dialog; after the user clicks it, the browser will then proceed through to the actual link:

$(document).ready(function() {
    $('#exampleLink').click(function() {
        alert('You clicked the link.');
    });
});

Prevent the default action with reurn false

The second example below will also display the alert dialog but then will not follow the link.

$(document).ready(function() {
    $('#exampleLink').click(function() {
        alert('You clicked the link.');
        return false;
    });
});

Note that the return false line needs to be the last line in the function otherwise any code below it in the function will not execute. You could also return the value based on some condition e.g. return someVariable == 'foobar' - if it returns true then the link will be followed; if false it won't.

Prevent the default action with preventDefault()

The final example below will again show the alert dialog and will not follow the link.

$(document).ready(function() {
    $('#exampleLink').click(function(e) {
        e.preventDefault();
        alert('You clicked the link.');
    });
});

Unlike the return false example, e.preventDefault() can be anywhere in the function and the rest of the code in the function will still be executed. I've put it at the start of the function but it could just as easily be at the end or some middle point.



Related posts:


Comments