How to enable or disable an anchor using jQuery?
Accepted Answer
To prevent an anchor from following the specified href
, I would suggest using preventDefault()
:
// jQuery 1.7+
$(function () {
$('a.something').on("click", function (e) {
e.preventDefault();
});
});
// jQuery < 1.7
$(function () {
$('a.something').click(function (e) {
e.preventDefault();
});
// or
$('a.something').bind("click", function (e) {
e.preventDefault();
});
});
See:
http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29
Also see this previous question on SO:
Popular Answer
The app I'm currently working on does it with a CSS style in combination with javascript.
a.disabled { color:gray; }
Then whenever I want to disable a link I call
$('thelink').addClass('disabled');
Then, in the click handler for 'thelink' a tag I always run a check first thing
if ($('thelink').hasClass('disabled')) return;
Read more... Read less...
I found an answer that I like much better here
Looks like this:
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
Enabling would involve setting the href attribute
$(document).ready(function(){
$("a").click(function () {
$(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html");
});
});
This gives you the appearance that the anchor element becomes normal text, and vice versa.
I think a nicer solution is to set disabled data attribute on and anchor an check for it on click. This way we can disable temporarily an anchor until e.g. the javascript is finished with ajax call or some calculations. If we do not disable it, then we can quickly click it a few times, which is undesirable...
$('a').live('click', function () {
var anchor = $(this);
if (anchor.data("disabled")) {
return false;
}
anchor.data("disabled", "disabled");
$.ajax({
url: url,
data: data,
cache: false,
success: function (json) {
// when it's done, we enable the anchor again
anchor.removeData("disabled");
},
error: function () {
// there was an error, enable the anchor
anchor.removeData("disabled");
}
});
return false;
});
I made a jsfiddle example: http://jsfiddle.net/wgZ59/76/
Selected Answer is not good.
Use pointer-events CSS style. (As Rashad Annara suggested)
See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events. Its supported in most browsers.
Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:
a[disabled], a[disabled]:hover {
pointer-events: none;
color: #e1e1e1;
}
Try the below lines
$("#yourbuttonid").attr("disabled", "disabled");
$("#yourbuttonid").removeAttr("href");
Coz, Even if you disable <a>
tag href
will work so you must remove href
also.
When you want enable try below lines
$("#yourbuttonid").removeAttr("disabled");
$("#yourbuttonid").attr("href", "#nav-panel");