Detecting when the mouse is not moving

后端 未结 7 720
逝去的感伤
逝去的感伤 2021-01-31 05:06

I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn\'t moved for more than 1 minute, then we have to alert the user.

7条回答
  •  梦谈多话
    2021-01-31 05:14

    Here's a one-and-done function that can check any element for movement:

    function mouse (element, delay, callback) {
    
       // Counter Object
       element.ms = {};
    
       // Counter Value
       element.ms.x = 0;
    
       // Counter Function
       element.ms.y = function () {
    
          // Callback Trigger
          if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
       };
    
       // Counter Callback
       element.ms.callback = callback;
    
       // Function Toggle
       element.ms.toggle = function (state) {
    
          // Stop Loop
          if ([0, "off"][state]) clearInterval(element.ms.z);
    
          // Create Loop
          if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
       };
    
       // Function Disable
       element.ms.remove = function () {
    
          // Delete Counter Object
          element.ms = null; return delete element.ms;
       };
    
       // Function Trigger
       element.onmousemove = function () {
    
          // Reset Counter Value
          element.ms.x = -1;
       };
    
       // Return
       return element.ms;
    };
    

    Usage: mouse(element, delay, callback)

    Examples: Make a video player hide the mouse after 5 seconds when idle and fullscreen

    let x = mouse(video, 5000, function (a) {
       if (document.webkitIsFullScreen) video.style.cursor = "none";
    });
    
    x.toggle(1); addEventListener("mousemove", function () {
       video.style.cursor = "auto";
    });
    

    Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):

    let x = mouse(chatBox, (45e3), function (a) {
       chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
    });
    
    x.toggle(1); x.addEventListener("mousemove", function () {
      chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
    });
    

提交回复
热议问题