Search code examples
javascripthtmlmotionevent

How can I track mouse move events in javascript once the cursor is off of the target element?


I can get mouse motion events in javascript using a simple function:

myElement.onmousemove(function(event){
  // ...
});

but I think those events only fire when the cursor is hovering over the element. I know I can also do this for document and get all mouse motion events:

document.onmousemove(function(event){...});

However, this event doesn't have the "scope" of belonging to the div or button or whatever, and won't have an offset relative to the element I'm working with.

My workaround is to save a variable pointing at the focused div and reference it when getting all motion events, but I'd much rather get motion events and the onmousemove function set for the element itself. Is there a way for that element to continue receiving mouse move events even if the cursor leaves the boundary of the element?

In case it matters I can use jQuery but I would prefer a native solution.


Solution

  • no, it is not possible to get a mousemove event when the movement is outside of the attached element. As you stated correctly, you can track the movement on the document. When using that together with mouseenter and mouseleave events, you can set/unset a variable to indicate if the movements are happening on the element or not.

    e.g.

    var myElement = document.getElementById("special");
    var isOverMyElement = false;
    document.addEventListener('mousemove', function(e){
        if (isOverMyElement){
            console.log("mouse is within myelement at details", e);
        }
    })
    myElement.addEventListener('mousenter', function(e){
        isOverMyElement = true;
    })
    myElement.addEventListener('mousenter', function(e){
        isOverMyElement = false;
    })
    

    If you are targeting older browsers, use jQuery as it normalizes mouseenter/leave over browsers. If you are targeting modern browsers, there is no need for jQuery