3

I need to find a global way to prevent jQuery on('click') events from firing if an anchor has the disabled="disabled" (yes im aware this isn't a valid attribute of an anchor) attribute set. The anchor could also be dynamically set to disabled at any time.

Another problem is firing order as im working within a "framework" and the App class loads first and subsequent classes with anchor events load after. Ideally id like to have something inside the App class that prevents the "child" class events from firing but at the moment the child class events fire first and then the App events so using stopPropagation() doesn't work either.

I'm wary of some solutions like How to order events bound with jQuery as you can see this could break between jQuery versions.

Community
  • 1
  • 1
Wancieho
  • 708
  • 1
  • 7
  • 25

1 Answers1

5

Delegating event would work if click event propagation not stopped:

$(document).on('click', 'a[disabled]', function(e){
  e.preventDefault();
});

Otherwise, you could use CSS rule:

a[disabled] {
  pointer-events: none;
}

And if you want an event to fire on parent level before any of its descendants, capture it, e.g:

document.addEventListener('click', function(e){
  if($(e.target).closest('a[disabled]').length) {
    // do something which be fired before any click handler bound to `.parentClass *`
    // e.g prevent any other event
    e.stopImmediatePropagation();
    // and prevent default anchor click behaviour
    e.preventDefault();
  }
}, true);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • This does not prevent any events from firing, which is what the OP seems to have in mind. – Tomalak Sep 06 '16 at 09:44
  • @GüvenAltuntaş `disabled` is boolean attribute, `disabled="donotdisable"` hasn't any meaning even on element where `disabled` has any purpose (which isn't the case on anchor anyway) – A. Wolff Sep 06 '16 at 09:45
  • @Tomalak I was guessing OP wants to prevent default behaviour but rereading question, i guess you are right. But using CSS rule would for any mouse events and for IE>8 – A. Wolff Sep 06 '16 at 09:47
  • @Wancieho No it won't here because you are capturing event. It would only if other click event are bound before and captured at same level (document) which i guess this is absolutely not the case. So did you try it??? EDIT: see jsfiddle: https://jsfiddle.net/ty52z675/ – A. Wolff Sep 06 '16 at 10:02