swelet
swelet

Reputation: 8722

Offset a mouse click to occur somewhere else

Ok so just got a very strange requirement in an app that I am building. I need a mouse click to occur 50 px to the right of the cursor position. That is, when the user clicks in one place - the event should be registered 50 px to the right.

Is this even possible?

Upvotes: 0

Views: 114

Answers (1)

thanksd
thanksd

Reputation: 55664

You can do this by preventing pointer events on the body and then temporarily allowing them in a document.onclick handler. Then simulate a click using document.elementFromPoint (taken from this question). Just add 50 to the offsetX value of the initial click event.

script:

let $body = $('body');
$body.addClass('locked');

document.onclick = function(e) {
  $body.removeClass('locked');
  let el = document.elementFromPoint(e.offsetX + 50, e.offsetY);
  if (el) {
    el.click();
  }
  $body.addClass('locked');
};

css:

body.locked {
  pointer-events: none;
}

Upvotes: 1

Related Questions