Programmatically click on a non-button element using javascript?
javascript
Solution
Believe it or not, for a fairly basic click, you can just call `click` on it (but more below): Live Example | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Artificial Click</title>
</head>
<body>
<div id="foo">xxxxxxx</div>
<script>
(function() {
var foo = document.getElementById("foo");
foo.addEventListener("click", function() {
display("Clicked");
}, false);
setTimeout(function() {
display("Artificial click:");
foo.click(); // <==================== The artificial click
}, 500);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
You can also create the relevant type of `Event` object and use `dispatchEvent` to send it to the element:
var e = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true
});
foo.dispatchEvent(e);
This gives you the opportunity to do things like set other information (the typical `pageX` and `pageY`, for instance) on the event you're simulating.
More about the various event object types in Section 5 of the DOM Events spec.
Problem
How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?