How to simulate a click using x, y coordinates in JavaScript?

Is it possible to use the given coordinates to simulate a click in JavaScript on a web page?

+63
javascript jquery html mouseclick-event mouseevent
Jul 18 '10 at 21:40
source share
4 answers

You can send a click event, although this is not the same as a real click. For example, it cannot be used to trick a cross-domain iframe document into thinking that it was clicked.

All modern browsers support document.elementFromPoint and HTMLElement.prototype.click() , since at least IE 6, Firefox 5, any version of Chrome, and possibly any version of Safari that you probably want about. It will even follow links and submit forms:

 document.elementFromPoint(x, y).click(); 

https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

+103
Jul 18 '10 at 21:56
source share

Yes, you can simulate a mouse click by creating an event and sending it:

 function click(x,y){ var ev = document.createEvent("MouseEvent"); var el = document.elementFromPoint(x,y); ev.initMouseEvent( "click", true /* bubble */, true /* cancelable */, window, null, x, y, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); el.dispatchEvent(ev); } 

Beware of using the click method for an element - it is widely implemented, but it is not standard and will not work, for example. PhantomJS. I assume that the jQuery .click() implementation does the right thing, but is not confirmed.

+43
May 12 '13 at 16:32
source share

This is just a torazaburo answer updated to use a MouseEvent object.

 function click(x, y) { var ev = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true, 'screenX': x, 'screenY': y }); var el = document.elementFromPoint(x, y); el.dispatchEvent(ev); } 
+16
Mar 22 '16 at 1:28
source share

For security reasons, you cannot move the mouse cursor using javascript and not simulate a click with it.

What are you trying to accomplish?

+1
Jul 18 '10 at 21:50
source share



All Articles