0

I have a legacy code that has something like

<a href='#' onclick="javascript:Domystuff(); return false;"> Some text<a>

I add a jQuery for some other purpose in website, and now I want to detect if this given a tag has "onclick" event available or not. But I didn't found how can I do this. I see most suggest to use $("a").data('events') but that didn't work for me, and always give undefined. however when I call $("a").click() it does execute the Domystuff() function.

Any idea how can I detect if onclick or onchange or onblur like HTML attribute events are present or not.

EDIT: I forgot to mention that I don't just want to detect all events from attributes but I want all events on element for click or blur or change. Hope I make myself clear now. Thanks

2
  • Related question: stackoverflow.com/questions/446892/… Commented Jan 9, 2014 at 11:59
  • @simone not quite related, as I see, as I want to check if all events through code, not in debug environment. Commented Jan 9, 2014 at 12:25

2 Answers 2

2
if($('a').attr('onclick')) { // exists
}

after all, even eventhandlers are HTML - attributes. Still, that won't detect eventhandlers attached by jQuery, so:

 var ahrefs = $('a');
 for(var i = 0;i < ahrefs.length;i++) {
    var node = ahrefs.get(i);

    if(typeof node.onClick == function) { // has an attached event handler
    }
 }

Easy, isn't it?

Sign up to request clarification or add additional context in comments.

1 Comment

+1, it is funny that I already think of it, but this doesn't quite solve my problem. but yes it is one of options to do. actually it is my fault I didn't mention that I want to detect all events doesn't matter how they get attached to element, not just with attribute. Atleast those who are added from jquery and attribute both.
1

try something like this

 if ($('a').attr("onClick") != undefined) {}

1 Comment

You can also try to be more specific in your selector. $("a") is fairly greedy, but if you add a class $("a.myClass") it will only hit that element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.