How to move mouse pointer to a specific position using JavaScript ?
In this article, we will learn how to move a mouse pointer to any specific position in the web browser using JavaScript. Before we start, you need to know that it’s not actually possible to move the mouse pointer to a position using Javascript, such functionality can be easily misused but we can simulate something similar. In this article, we will learn to move the mouse pointer from one pointer to another pointer.
- Since we cannot make an actual mouse pointer using JavaScript, we use an image as a cursor.
- Suppose variables x, y, px, py, x1, x2
x: x-position of the actual mouse pointer
y: y-position of the actual mouse pointer
x1: x-position where we want the mouse to appear
x2: y-position where we want the mouse to appear
Now, let
x + px = x1
px = x1 - x
similarly,
py = y1 - y
Now, px, py is the relative position of x, y with respect to x1, y1.
The position where our image cursor will appear with respect to x1,
y1 will be given by
x + px and y + py
for all x, y
- Now, the problem is how to detect clicks since the mouse cursor may not be on the pointer. To do this, we use document.elementFromPoint(x+px, y+py) in which we pass the position of the image cursor. This will give us the object of the element, the image cursor is on. After obtaining the required object, we can invoke the object.click().
Example: This example shows the movement of the mouse pointer to a specific position using JavaScript
html
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "utf-8" />
</ head >
< body >
< img id = "cursor" src =
width = "15" height = "20" />
< p >
< button id = "b1" >BUTTON1</ button >
</ p >
< p >
< button id = "b2" >BUTTON2</ button >
</ p >
</ body >
</ html >
|
CSS
img {
pointer-events: none ;
position : absolute ;
}
* {
cursor : none ;
}
|
Javascript
let x, y;
let px, py;
px = py = 0;
let cursor = document.getElementById( "cursor" );
let b1 = document.getElementById( "b1" );
let b2 = document.getElementById( "b2" );
let mutex = false ;
window.addEventListener( "mouseup" , function (e) {
let tmp = document.elementFromPoint(x + px, y + py);
mutex = true ;
tmp.click();
cursor.style.left = (px + x) + "px" ;
cursor.style.top = (py + y) + "px" ;
})
window.addEventListener( "mousemove" , function (e) {
x = e.clientX;
y = e.clientY;
cursor.style.left = (px + x) + "px" ;
cursor.style.top = (py + y) + "px" ;
});
b1.onclick = function () {
if (mutex) {
mutex = false ;
px = b2.offsetLeft - x;
py = b2.offsetTop - y;
}
}
b2.onclick = function () {
if (mutex) {
mutex = false ;
px = b1.offsetLeft - x;
py = b1.offsetTop - y;
}
}
|
Output: Click here to check the live output
Last Updated :
02 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...