Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the value of "onclick" with jQuery?

Is it possible to get the current value of the onClick attribute of an A tag via jQuery?

For example, I have:

<a href="http://www.google.com" id="google" onclick="alert('hello')">Click</a> 

I want to get the onclick code so I can store it for later use (as I'll be changing the onclick event for a little while).

Is it possible to do something like:

var link_click = $("#google").onclick; 

or:

var link_click = $("#google").click; 

So that later on in my code I can re-apply that code, or eval() it if necessary?

like image 566
Mike Trpcic Avatar asked Sep 12 '09 17:09

Mike Trpcic


People also ask

How can use onclick function in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

What does the onclick attribute do?

The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.


2 Answers

i have never done this, but it would be done like this:

var script = $('#google').attr("onclick") 
like image 109
mkoryak Avatar answered Oct 02 '22 17:10

mkoryak


mkoryak is correct.

But, if events are bound to that DOM node using more modern methods (not using onclick), then this method will fail.

If that is what you really want, check out this question, and its accepted answer.

Cheers!


I read your question again.
I'd like to tell you this: don't use onclick, onkeypress and the likes to bind events.

Using better methods like addEventListener() will enable you to:

  1. Add more than one event handler to a particular event
  2. remove some listeners selectively

Instead of actually using addEventListener(), you could use jQuery wrappers like $('selector').click().

Cheers again!

like image 23
jrharshath Avatar answered Oct 02 '22 16:10

jrharshath