3

How can I trigger mouse left button click by specifying X and Y pixels offset from upper left website corner via JavaScript?

Ivan Doroshenko
  • 944
  • 7
  • 13

5 Answers5

3

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 */});
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
1

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)
};
Girish
  • 11,907
  • 3
  • 34
  • 51
  • I have no clicks, but I have to issue/trigger a click. So subscribing to any events is not a solution. – Ivan Doroshenko Apr 01 '14 at 13:03
  • @IvanDoroshenko i'm not sure what are you mean exactly, this code is bide whole body in click event, you can only get specified x,y values in `if` condition this is also fake trigger click – Girish Apr 01 '14 at 13:09
0

Use 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.

Starscream1984
  • 3,072
  • 1
  • 19
  • 27
0

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
    }
});
Starscream1984
  • 3,072
  • 1
  • 19
  • 27
QBM5
  • 2,778
  • 2
  • 17
  • 24
0

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?

Community
  • 1
  • 1
Ivan Doroshenko
  • 944
  • 7
  • 13