Gideon Gideon - 7 months ago 10
Javascript Question

Retrieve onclick listeners of an <a> tag and remove to make it 'disabled'


First of all, this problem originates from the fact the
HTML
anchor cannot be set to
disabled
.


I have a lot of anchors (the
<a>
tag) in my site that serves as button, lists, menu items, etc. They cannot be disabled but under some circumstances, I need to disable them. To make them disabled I'm planning to do the following:


  1. Add class to the specific anchor that will make them grey-ed out and "unclickable".

  2. Temporarily remove all it
    onclick
    events and reattach it after. I plan to do this by:


    1. Retrieving all the
      onclick
      handlers and saving it to an
      Array
      of
      functions()
      to be retrieved later, in case you want to enable it again later. (I don't know how to do this yet!)

    2. Then remove all the
      onclick
      listeners




I'm asking a way to retrieve only handlers for onclick events, but all I see is about retrieving all types of attached events.




EDIT : Guys, I appreciate the answers on how to disable anchors... but [you know, ] that is not my question. Some of the solutions are not possible on my scenario (too complicated to discuss here), and the solution above is currently the easiest thing that I can do. What I really want to know is how to perform something like this:

var handlers = []
handlers = $("#anchor").getClickEvents()

Answer

You can try something like this:

$('body').on('click', 'a:not(.disabled)', function(){
    console.log($(this).text() + ' was clicked');
}).on('click', 'a.disabled', function(e){
    e.preventDefault();
});

$('a').trigger('click');
$('a.disabled').removeClass('disabled');
$('a').trigger('click');

Assign the .on event to the anchors parent so any changes will be taken in consideration.

The HTML in the demo:

<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
<a href="#" class="disabled">4</a>

Here is a demo

Comments