Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a click with JavaScript?

Tags:

javascript

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?

like image 656
Belgin Fish Avatar asked Apr 24 '10 18:04

Belgin Fish


People also ask

How do you make a click in JavaScript?

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.

What is click event in JavaScript?

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.

How do you simulate a mouse event?

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.


2 Answers

What about something simple like:

document.getElementById('elementID').click(); 

Supported even by IE.

like image 94
StudioTime Avatar answered Sep 20 '22 09:09

StudioTime


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'); 
like image 37
KooiInc Avatar answered Sep 19 '22 09:09

KooiInc