I'm just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
function simulateClick(control) { if (document.all) { control.click(); } else { var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); control.dispatchEvent(evObj); } }
<a href="http://www.google.com" id="mytest1">test 1</a><br> <script type="text/javascript"> simulateClick(document.getElementById('mytest1')); </script>
But it's not working :(
Any ideas?
Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
An easier and more standard way to simulate a mouse click would be directly using the event constructor to create an event and dispatch it. Though the MouseEvent. initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.
What about something simple like:
document.getElementById('elementID').click();
Supported even by IE.
Here's what I cooked up. It's pretty simple, but it works:
function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } }
Usage:
eventFire(document.getElementById('mytest1'), 'click');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With