How to simulate mouse click along with mouse move using javascript

22,348

Solution 1

You cannot move the mousepointer with javascript, because of the security implications that it incurs.

Solution 2

As already pointed out in other answers, you can't change the real mouse position with JavaScript... but... do you need to do that? No!

You can add a image of a mouse cursor and place that on any position you want on top of your content, relative to the browser window top-left. You can hide the real cursor by applying css 'cursor: none;' class to the zone of the screen you want the cursor to disappear.

So to simulate what you want you can get the position of the element you want to click, hide real mouse cursor, show fake mouse cursor and move that one to the position of the element you want to click, then click it.

To make it user friendly: please notify the user to not move his mouse anymore when you start the simulation, simulate mouse move and click, when user moves his mouse hide the fake mouse and show real mouse and notify user that simulation is over.

Solution 3

You can't change mouse cursor postion in browser. see this.

But you can use javascript click() method to simulate click event. To do this work you must use elementFromPoint() to select click position. In my bottom example when you click on first button, javascript simulate second button click.

var first = document.getElementById("first");
var second = document.getElementById("second");

first.addEventListener("click", function(){ 
    var xPos = second.offsetLeft;
    var yPos = second.offsetHeight;
    document.elementFromPoint(xPos, yPos).click();
});

second.addEventListener("click", function(){ 
    alert("Second button clicked!");
});
<button id="first">First</button>
<button id="second">Second</button>
Share:
22,348
HimaaS
Author by

HimaaS

Updated on July 09, 2022

Comments

  • HimaaS
    HimaaS almost 2 years

    I am using simulation for mouse click operation using element.click() in js file, but mouse cursor is some where else and action is performing on correct element, i want to have mouse cursor on element while performing the simulate mouse click.Does anyone know using javascript code, how can i get this?