I have an element with an onclick method.
I would like to activate that method (or: fake a click on this element) within another function.
Is this possible?
I have an element with an onclick method.
I would like to activate that method (or: fake a click on this element) within another function.
Is this possible?
just call "onclick"!
here's an example html:
If you're using jQuery, you need to use the
.trigger
function, so it would be something like:http://api.jquery.com/trigger/
You can also try getting the element's onclick attribute and then passing into eval. This should work despite the big taboo over eval. I put a sample below
This is a perfect example of where you should use a javascript library like Prototype or JQuery to abstract away the cross-browser differences.
element.dispatchEvent
is supported in all major browsers. The example above is based on an samplesimulateClick()
function on MDN.I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:
Now, whenever this element is clicked, the code in
clickHandler
will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assignclickHandler
to handle events triggered by other elements)>