1

I see some anchor elements on an html page like so

<a href="javascript:void(0);" class="clickable">Click me</a>;

The page assigns JavaScript event handlers to the anchor element on page load. After the page loads, I can click on the anchor element to fire a JavaScript operation.

I want to programmatically fire the anchor's event handler function, but I am unable to determine the event handler's function name because the relevant external JavaScript file is compressed, so it's difficult to trace the code. The compression obfuscated all the variable/function names and put everything on one line.

Can anyone suggest a way for me to programmatically fire the anchor's onclick event handler?

Thanks

Shog9
  • 156,901
  • 35
  • 231
  • 235
John
  • 32,403
  • 80
  • 251
  • 422

2 Answers2

2

To answer the question in your title: no, you can't. You can't get the name because there might not even be a name - it's become quite common to use anonymous functions for this purpose.

For the answer to your second question, see:

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
0

Is an alternative solution viable? Clicking on the link to invoke it's handler to simulate a user clicking, instead of trying to find the handler?

Something like this in jQuery:

$("a.clickable:first").click();

Update: Here's a working example to show how this works on DOM:

<html>
 <head></head>
 <body>
  <a href="javascript:void(0)" onclick="alert('I'm an alert!')">Click me</a>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script type="text/javascript">
   $(function() { $('a').click(); });
  </script>
 </body>
</html>
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    I guess this solution will not work because, I believe, jQuery does not dispatch native DOM-Events events into browser DOM implementation. Instead it probably only invokes those handlers added through jQuery API. – Sergey Ilinsky Jan 19 '10 at 23:30
  • @Sergey Ilinsky: I just tested this, it does work, `Click me` with `$('a').click();` does fire the alert. I added a full example page above so you can test it out as well. – Nick Craver Jan 19 '10 at 23:55
  • 1
    jQuery attempts to execute all event handlers, whether declared inline, bound using `addEventListener` or `attachEvent`, or bound using jQuery. Take a look at this demo - http://jsbin.com/owugu/edit and click on the output tab. Check the code under the JavaScript tab – Russ Cam Jan 20 '10 at 00:06