How to enable or disable an anchor using jQuery?
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;
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:
jQuery disable a link
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.