Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate click at x/y coordinates using javascript

How can I simulate a click at x/y co-ordinates using javascript or jquery?

I will use the script multiple times and I want the script to click on postion one then postion two then three then four and so one.

It is better without moving the mouse cursor, but if it has to move then that is fine as well.

like image 240
Ahmed Hafez Avatar asked Apr 24 '12 20:04

Ahmed Hafez


People also ask

How do you use the click method in JavaScript?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do I get X and Y in JavaScript?

To get the X and Y coordinates for a div element with JavaScript, we an use the getBoundingXClientRect method. to select the div with querySelector . And then we call getBoundingClientRect to get the position of the div. Then we get the x and y coordinates of the div with position.

How do I find the x and y coordinates of a website?

In order to find the coordinates of the top left corner of the HTML page, you can use the web browser's instance properties DisplayRectangleX and DisplayRectangleY. For example, after storing a browser's instance into the variable %Browser%, then %Browser. DisplayRectangleX% will return the X dimension and %Browser.


2 Answers

This can actually be accomplished with the document.elementFromPoint method. A jQuery example:

function simulateClick(x, y) {
    jQuery(document.elementFromPoint(x, y)).click();
}
simulateClick(100, 250);
simulateClick(400, 250);

Edit: Here is a working example: http://jsfiddle.net/z5YjY/

like image 163
Prestaul Avatar answered Sep 18 '22 05:09

Prestaul


On a second take, I'd share my experiences, and update Prestaul's answer.

In most cases, you don't just want to click on an element to induce the 'onclick' event, but you would like to use the click info for something (eg.: move a slider there, or put a popup at that exact place).

I'm mostly using vanilla js, but it blends well with $.

function simulateClick(x, y) {
    var clickEvent= document.createEvent('MouseEvents');
    clickEvent.initMouseEvent(
    'click', true, true, window, 0,
    0, 0, x, y, false, false,
    false, false, 0, null
    );
    document.elementFromPoint(x, y).dispatchEvent(clickEvent);
}

Basically this will pass down the correct pageX / pageY through the event, for further use.

I have updated the fiddle as well, to show a use of these coords: http://jsfiddle.net/V4CdC/

like image 25
Alex Avatar answered Sep 19 '22 05:09

Alex