Disable a link from going to the href URL with jQuery
Posted September 12th, 2011 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="http://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:
- Prevent an AJAX request firing twice with jQuery (Tuesday, September 13th 2011)
- Style HTML Anchor Titles with jQuery and CSS (Thursday, June 2nd 2011)
- Target links to _top with jQuery (Wednesday, July 21st 2010)
- jQuery: set title of anchor tags to the href for offsite links (Tuesday, July 6th 2010)
- Assign and remove a click handler from an element with jQuery (Tuesday, December 1st 2009)

Comments
blog comments powered by Disqus