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?
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?
Share Improve this question asked May 11, 2016 at 5:25 HimaaSHimaaS 4233 gold badges6 silver badges13 bronze badges 5- 1 will you please show what you have tried. And is necessary that you use only vanilla javascript what about jQuery. – Manish Commented May 11, 2016 at 5:30
- 1 mouse cursor is some where else and action is performing on correct element .. what does it mean ..?? Then you might be using onmousemove event for the specific div – Suresh Commented May 11, 2016 at 5:34
- I have used just element.click(); for performing the action on my element.can u provide how to make cursor also on that element. – HimaaS Commented May 11, 2016 at 6:04
- I have to use javascript only. – HimaaS Commented May 11, 2016 at 6:04
- Possible duplicate of Move the mouse pointer to a specific position? – Mohammad Commented Nov 2, 2018 at 8:49
4 Answers
Reset to default 5As 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.
You cannot move the mousepointer with javascript, because of the security implications that it incurs.
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>
I found a git-repository that simulates a mouse-drag event:
link to git-repository
SEE CODEPEN EXAMPLE HERE
useful article
HTML
<!--
author: kemokid
github: https://github.com/kemokid/scripting-sortable/blob/master/script_sortable_dnd_more_general.js
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<!-- https://ghostinspector.com/blog/simulate-drag-and-drop-javascript-casperjs/ -->
<p>Drag the W3Schools image into the rectangle:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="https://www.w3schools.com/html/img_logo.gif" ondragstart="drag(event)" >
<br/>
<button onClick="autodrag();">Auto-drag</button>
<br/>
<br/>
Reload the page to reset the image.
<script src="app.js"></script>
</body>
</html>
CSS
/*
author: kemokid
github: https://github.com/kemokid/scripting-sortable/blob/master/script_sortable_dnd_more_general.js
*/
#div1 {
width: 350px;
height: 70px;
padding: 10px;
border: 1px solid #aaaaaa;
}
#drag1 {
width: 336px;
height: 69px;
}
JS
/*
author: kemokid
github: https://github.com/kemokid/scripting-sortable/blob/master/script_sortable_dnd_more_general.js
*/
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var id = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(id));
}
function autodrag() {
return triggerDragAndDrop('#drag1', '#div1');
}
// Originally from https://ghostinspector.com/blog/simulate-drag-and-drop-javascript-casperjs/
// trimmed down and modified by @kemokid (Martin Baker) to work with Sortable.js
///
// Probably not going to work with dragging from one list to another
// This has been made more general, to work with other drag-and-drop elements besides a
// Sortable list, but is not as complete as the Casper example above.
// Call with DOM selectors, eg `triggerDragAndDrop('#drag', '#drop');`
// Returns false if unable to start.
// callback, if present, will be called with true if able to finish, false if not.
// If you receive "false" on the callback, the list is likely not in the beginning state.
var triggerDragAndDrop = function (selectorDrag, selectorDrop, callback) {
var DELAY_INTERVAL_MS = 10;
var MAX_TRIES = 10;
var dragStartEvent;
// fetch target elements
var elemDrag = document.querySelector(selectorDrag);
var elemDrop = document.querySelector(selectorDrop);
if (!elemDrag || !elemDrop) {
console.log("can't get elements");
return false;
}
var startingDropRect = elemDrop.getBoundingClientRect();
function rectsEqual(r1, r2) {
return r1.top === r2.top && r1.right === r2.right && r1.bottom === r2.bottom && r1.left === r2.left;
}
// function for triggering mouse events
function fireMouseEvent(type, elem, dataTransfer) {
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent(type, true, true, window, 1, 1, 1, 0, 0, false, false, false, false, 0, elem);
if (/^dr/i.test(type)) {
evt.dataTransfer = dataTransfer || createNewDataTransfer();
}
elem.dispatchEvent(evt);
return evt;
};
function createNewDataTransfer() {
var data = {};
return {
clearData: function(key) {
if (key === undefined) {
data = {};
} else {
delete data[key];
}
},
getData: function(key) {
return data[key];
},
setData: function(key, value) {
data[key] = value;
},
setDragImage: function() {},
dropEffect: 'none',
files: [],
items: [],
types: [],
// also effectAllowed
}
};
// trigger dragging process on top of drop target
// We sometimes need to do this multiple times due to the vagaries of
// how Sortable manages the list re-arrangement
var counter = 0;
function dragover() {
counter++;
console.log('DRAGOVER #' + counter);
var currentDropRect = elemDrop.getBoundingClientRect();
if (rectsEqual(startingDropRect, currentDropRect) && counter < MAX_TRIES) {
if (counter != 1) console.log("drop target rect hasn't changed, trying again");
// mouseover / mouseout etc events not necessary
// dragenter / dragleave events not necessary either
fireMouseEvent('dragover', elemDrop, dragStartEvent.dataTransfer);
setTimeout(dragover, DELAY_INTERVAL_MS);
} else {
if (rectsEqual(startingDropRect, currentDropRect)) {
console.log("wasn't able to budge drop target after " + MAX_TRIES + " tries, aborting");
fireMouseEvent('drop', elemDrop, dragStartEvent.dataTransfer);
if (callback) callback(false);
} else {
setTimeout(drop, DELAY_INTERVAL_MS);
}
}
}
function drop() {
console.log('DROP');
// release dragged element on top of drop target
fireMouseEvent('drop', elemDrop, dragStartEvent.dataTransfer);
fireMouseEvent('mouseup', elemDrop); // not strictly necessary but I like the symmetry
if (callback) callback(true);
}
// start dragging process
console.log('DRAGSTART');
fireMouseEvent('mousedown', elemDrag);
dragStartEvent = fireMouseEvent('dragstart', elemDrag);
// after a delay, do the first dragover; this will run up to MAX_TRIES times
// (with a delay between each run) and finally run drop() with a delay:
setTimeout(dragover, DELAY_INTERVAL_MS);
return true;
};