javascripthtmldom-eventsleap-motion

Javascript click simulation on a page


I am currently working on a project using a LeapMotion with a Javascript/html front-end. I would like to control the entire application with the LeapMotion (including clicking, click and drag, etc.). However, I have run into a bit of a problem.

I would like to trigger a MouseEvent("click"), however, I do not want to trigger the event on a specific element (as discussed here). This is because I do not want to have to "manually" check for which element my LeapMotion cursor is over and call the trigger on it. Instead I would like to trigger a more "pure" click event in which Javascript determines what is being clicked. Is something like this possible? If not, are there any reasonable work arounds?

EDIT: Some more information. I can currently determine in my code when I need to trigger a click event based on data from the LeapMotion. My problem is that I need a way to trigger a click event on the page. Currently, the solutions I have found can create a MouseEvent but they then have to call it on a specific div/element/etc. I would like to trigger a more "global" MouseEvent such that I can trigger it on the page instead of a specific element.


Solution

  • For anyone having a similar problem in the future, here is how I ended up solving this.

    The LeapMotion is updating the position of a "cursor" object in the screen. When I determine a click is being executed by the user, I perform the following:

    1. Get the position of the cursor (some calculation went into this to reference the center of the cursor instead of the top and left offset that javascript will give you)
    2. Using document.elementFromPoint(x, y) I retrieved the element the cursor is currently hovering over (some parsing may be required here if there are elements overlapping each other).
    3. Create a MouseEvent as follows and dispatch it to the element.

      var evt = new MouseEvent("mousedown", function(){
          view: window,
          cancelable: true,
          clientX: x,
          clientY: y
      });
      element.dispatchEvent(evt);
      

    I should also note that I needed to differentiate between mousedown, mouseup, click, and mousemove events. Therefore, there is some logic in determining which event to send. However, I only retrieve the element by its position once (in the mousedown event call) in order to tolerate some movement in the user's hand while clicking.

    It is not the best solution, but it is working quite well. Hopefully this helps!