[jquery] How to enable or disable an anchor using jQuery?

How to enable or disable an anchor using jQuery?

This question is related to jquery html anchor

The answer is


It's as simple as return false;

ex.

jQuery("li a:eq(0)").click(function(){
   return false;
})

or

jQuery("#menu a").click(function(){
   return false;
})

If you are trying to block all interaction with the page you might want to look at the jQuery BlockUI Plugin


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;
}

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/


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.


$('#divID').addClass('disabledAnchor');

In css file

.disabledAnchor a{
       pointer-events: none !important;
       cursor: default;
       color:white;
}

So with a combination of the responses above, I came up with this.

a.disabled { color: #555555; cursor: default; text-decoration: none; }

$(".yourClass").addClass("disabled").click(function(e){ e.preventDefault(); 

For situations where you must put text or html content within an anchor tag, but you simply don't want any action to be taken at all when that element is clicked (like when you want a paginator link to be in the disabled state because it's the current page), simply cut out the href. ;)

<a>3 (current page, I'm totally disabled!)</a>

The answer by @michael-meadows tipped me off to this, but his was still addressing scenarios where you still have to / are working with jQuery/JS. In this case, if you have control over writing the html itself, simply x-ing the href tag is all you need to do, so the solution is a pure HTML one!

Other solutions without jQuery finagling which keep the href require you to put a # in the href, but that causes the page to bounce to the top, and you just want it to be plain old disabled. Or leaving it empty, but depending on browser, that still does stuff like jump to the top, and, it is invalid HTML according to the IDEs. But apparently an a tag is totally valid HTML without an HREF.

Lastly, you might say: Okay, why not just dump the a tag altogether than? Because often you can't, the a tag is used for styling purposes in the CSS framework or control you're using, like Bootstrap's paginator:

http://twitter.github.io/bootstrap/components.html#pagination


If you don't need it to behave as an anchor tag then I would prefer to replace it at all. For example if your anchor tag is like

<a class="MyLink" href="http://www.google.com"><span>My</span> <strong>Link</strong></a>

then using jquery you can do this when you need to display text instead of a link.

var content = $(".MyLink").text(); // or .html()
$(".MyLink").replaceWith("<div>" + content + "</div>")

So this way, we can simply replace anchor tag with a div tag. This is much easier (just 2 lines) and semantically correct as well (because we don't need a link now therefore should not have a link)


$("a").click(function(event) {
  event.preventDefault();
});

If this method is called, the default action of the event will not be triggered.


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");

$("a").click(function(){
                alert('disabled');
                return false;

}); 

Disable or Enable any element with the disabled property.

// Disable 
$("#myAnchor").prop( "disabled", true );

// Enable
$( "#myAnchor" ).prop( "disabled", false );

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;

You never really specified how you wanted them disabled, or what would cause the disabling.

First, you want to figure out how to set the value to disabled, for that you would use JQuery's Attribute Functions, and have that function happen on an event, like a click, or the loading of the document.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to