Javascript: triggering a click eventΒΆ

Let’s assume we have this link, and we want to programmatically trigger a click on it.

<a href="javascript:void(0)" id="my-link">This is my link</a>

Usually, this should work:

document.getElementById('my-link').click();

but for some reason, that’s not always the case.

To solve the problem, I used this code, that generates a “mouse click” event and dispatches to the link/button.

var evObj = document.createEvent('MouseEvents');
evObj.initEvent('click', true, false);
document.getElementById('my-link').dispatchEvent(evObj);
comments powered by Disqus

Previous topic

Python: virtualenv hacks

Next topic

ANSI escape codes

This Page