tags:

views:

60

answers:

2

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

A: 

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"&gt;&lt;/script&gt;
  <script type="text/javascript">
   $(function() { $('a').click(); });
  </script>
 </body>
</html>
Nick Craver
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
@Sergey Ilinsky: I just tested this, it does work, `<a href="javascript:void(0)" onclick="alert('bob')">Click me</a>` with `$('a').click();` does fire the alert. I added a full example page above so you can test it out as well.
Nick Craver
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
+2  A: 

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?

Shog9