How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Ropstah picture Ropstah · May 25, 2009 · Viewed 231.1k times · Source

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>

Answer

Gumbo picture Gumbo · May 25, 2009

You need to apply the event handler in the context of that element:

var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
    elem.onclick.apply(elem);
}

Otherwise this would reference the context the above code is executed in.