0

I know that with jquery I can select an element and invoke a click. However, what I am looking to do is simply invoke a click on where ever the current cursor is.

For example something like this:

jQuery().click();
Yelitza
  • 23
  • 3

1 Answers1

0

I think this might help:

How to simulate a click by using x,y coordinates in JavaScript?

maybe something like:

$(document).click(function(e) {
   var x = e.clientX;
   var y = e.clientY;
   document.elementFromPoint(x, y).click();
})

Getting the user's mouse position can only be done via an event. Let's say your mouse is broken and it will track, but won't click, you could trigger a 'fake' click at the current position through other means:

var x, y;

$(document).mousemove(function(e) {
    x = e.clientX;
    y = e.clientY;
})

$(document).keyup(function(e) {
    // if the key pressed was return, click at the current cursor position
    if (e.keyCode === 13) {
        document.elementFromPoint(x, y).click();
    }
})

$(document).keyup(function(e) {
    // if the key pressed was space, click 50px below the current cursor position
    if (e.keyCode === 32) {
        document.elementFromPoint(x, y + 50).click();
    }
})

tested and working, now you can click with your keyboard!

Note that document.elementFromPoint(x, y) looks for elements at the coordinates relative to the viewport. So you'll be using e.clientX & e.clientY, not e.pageX & e.pageY.

Good Idea
  • 2,481
  • 3
  • 18
  • 25
  • I want to invoke the click not handle it if that makes sense. There is a long story behind this but it has to do with problems using a QA automation framework. – Yelitza Jul 08 '16 at 04:18
  • You need to get the current mouse position using an event. I've updated the answer above with some more on this. – Good Idea Jul 08 '16 at 05:05