Search code examples
javascriptjquerymouseeventjquery-events

Is there a way to trigger mousemove and get event.pageX, event.pageY?


So, like the question specifies, is there a way to trigger a mousemove event in jQuery which also sends the mouse coordinates to the event Object?

So far my code can trigger the mousemove using the .trigger(event) function but the event.pageX and event.pageY are undefined.


Solution

  • I don't believe it possible to get the mouse coordinates on demand via JavaScript / jQuery; however if you bind the position to a global var you can then access them at anytime throughout the document like this:

    $(document).ready(function(){
       $().mousemove(function(e){
          window.xPos = e.pageX;
          window.yPos = e.pageY;
       }); 
    });
    

    for a less CPU intensive option, you can add a timeout, although you trade performance for a slight delay in knowing where the mouse is:

    function getMousePosition(timeoutMilliSeconds) {
        $(document).one("mousemove", function (event) {
            window.xPos = event.pageX;
            window.yPos = event.pageY;
            setTimeout("getMousePosition(" + timeoutMilliSeconds + ")", timeoutMilliSeconds);
        });
    }
    getMousePosition(100);
    

    You should now be able to access the window.xPos and window.yPos from anywhere in the document using either solution without needing to trigger a faux event.