Simulate click at x/y coordinates using javascript

强颜欢笑 提交于 2019-11-30 10:05:27

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/

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!