Is it possible to programmatically invoke a onClick-event for an anchor tag, while maintaining the 'this' reference to the anchor?
The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click() is not a function)
<script type="text/javascript">
function doOnClick() {
document.getElementById('linkid').click();
//Should alert('/testlocation');
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.
I would suggest the following:
If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:
In general I would recommend against calling the event handlers 'manually'.
Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.
Have a look at the handleEvent method
https://developer.mozilla.org/en-US/docs/Web/API/EventListener
"Raw" Javascript:
Now click on your element (with id "myElement") and it should print the following in the console:
This allows you to have an object method as event handler, and have access to all the object properties in that method.
You can't just pass a method of an object to addEventListener directly (like that:
element.addEventListener('click',myObj.myMethod);
) and expectmyMethod
to act as if I was normally called on the object. I am guessing that any function passed to addEventListener is somehow copied instead of being referenced. For example, if you pass an event listener function reference to addEventListener (in the form of a variable) then unset this reference, the event listener is still executed when events are caught.Another (less elegant) workaround to pass a method as event listener and stil
this
and still have access to object properties within the event listener would be something like that:Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.
In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).
I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.
Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
You need to
apply
the event handler in the context of that element:Otherwise
this
would reference the context the above code is executed in.To trigger an event you basically just call the event handler for that element. Slight change from your code.