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?
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.
The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.
i have never done this, but it would be done like this:
var script = $('#google').attr("onclick")
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:
Instead of actually using addEventListener()
, you could use jQuery
wrappers like $('selector').click()
.
Cheers again!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With