Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable anchors in Chrome/WebKit/Safari

Consider the following code:

$("a").attr("disabled", "disabled");

In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes.

Do you have any suggestions on how to get the desired result. Answers must be:

  • Easily be revertable, since I want to disable form input controls while I have an AJAX call running.
  • Must work in IE, FF, and WebKit
like image 490
Stefan Rusek Avatar asked Oct 06 '08 17:10

Stefan Rusek


2 Answers

I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the "disabled" attribute and cancel the event if it is set. Your event handler would look something like this:

$("a").click(function(event){
  if (this.disabled) {
    event.preventDefault();
  } else {
    // make your AJAX call or whatever else you want
  }
});

You can also set a stylesheet rule to change the cursor.

a[disabled=disabled] { cursor: wait; }

Edit - simplified the "disabled" check as suggested in comments.

like image 108
Neall Avatar answered Oct 19 '22 14:10

Neall


I had to fix this behavior in a site with a lot of anchors that were being enabled/disabled with this attribute according to other conditions, etc. Maybe not ideal, but in a situation like that, if you prefer not to fix each anchor's code individually, this will do the trick for all the anchors:

$('a').each(function () {
    $(this).click(function (e) {
        if ($(this).attr('disabled')) {
            e.preventDefault();
            e.stopImmediatePropagation();
        }
    });
    var events = $._data ? $._data(this, 'events') : $(this).data('events');
    events.click.splice(0, 0, events.click.pop());
});

And:

a[disabled] {
    color: gray;
    text-decoration: none;
}
like image 33
hernant Avatar answered Oct 19 '22 15:10

hernant