How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?
5 Answers
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.
2 Comments
You can use HTMLElementObject.click()
Something like document.getElementById('div1').click()
See more
Comments
Or in jQuery (documentation) to click on a non-button element
$( "#nonButton" ).click();
or to listen for a click on that non-button element
$("#nonButton").on("click", doSomething);
1 Comment
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.getElementById("nonButton").dispatchEvent(evt);
see: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent