How can I trigger mouse left button click by specifying X and Y pixels offset from upper left website corner via JavaScript?
-
I have no clicks, but I have to issue/trigger a click. So subscribing to any events is not a solution.Ivan Doroshenko– Ivan Doroshenko2014-04-01 13:00:52 +00:00Commented Apr 1, 2014 at 13:00
-
Found the solution stackoverflow.com/questions/3277369/…Ivan Doroshenko– Ivan Doroshenko2014-04-01 13:10:42 +00:00Commented Apr 1, 2014 at 13:10
5 Answers
Well, using just Javascript as you asked, you can use mouse events, as you can read X and Y properties to get coordinaties from the event object, for sample:
// mouse move
document.body.onmousemove = function(e) {
var x = e.X;
var y = e.Y;
console.log(e);
}
// mouse down
document.body.onmousedown = function(e) {
var x = e.X;
var y = e.Y;
console.log(e);
}
To simulate an mouse click, you can call the event onmousedown manually, but you have to provide the event parameter (passing the coordinates, etc..), for sample:
document.body.onmousedown({X:120, Y:120 /* other properties */});
2 Comments
bind onclick event on document body, Try this code
document.body.onclick = function(e){
if(e.clientX < 100 && e.clientY < 100){
// your code here
}
alert("X =" + e.clientX +" Y"+ e.clientY)
};
2 Comments
if condition this is also fake trigger clickUse jquery mousemove to get the x y coords when moving and then fire the click within it if necessary. Something like:
$("body").mousemove(function( event ) {
if(event.pageX == 50 && event.pageY == 50)
{
$("targetclickelement").click();
}
});
Would be pretty inefficient though...
Edit - without jquery, use the same principle but with the handlers in Felipe Oriani's answer.
1 Comment
OP want to solution in JavaScript.I don't believe you can do such a thing, you could however catch the click then check the offsets and call function if it is within range
$('#d').click(function(event){
if(event.offsetX > 50 && event.offsetX < 100 && event.offsetY > 100 && event.offsetY < 200)
{
/// Execute function
}
});
1 Comment
You can fire an element's click event, and you can get an element using x/y co-ordinates - so you could fire a click event on the element at x/y. Since you tagged jQuery:
$(document.elementFromPoint(x, y)).click();
https://developer.mozilla.org/En/DOM:document.elementFromPoint
Solution from How to simulate a click by using x,y coordinates in JavaScript?