Search code examples
javajqueryhtmlcsscursor

Change mouse cursor on movement


I'm at bit of a loss on how to do this. The code I made works fine for changing the cursor on my website; however, I want it to only come into effect when the user moves the mouse, and then revert back to the default cursor when the user stops moving the mouse.

Here is my code so far:

<style type="text/css">body, a:hover {cursor: url(https://www.weebly.com/weebly/images/file_icons/image.png), progress !important;}</style>

Solution

  • You can use some JavaScript to add and remove a CSS class.

    Add a class to your CSS:

    .change-cursor {
      cursor: url(https://www.weebly.com/weebly/images/file_icons/image.png), progress !important;
    }
    

    And then in your JavaScript:

    var timeout;
    
    document.onmousemove = function() {
    
      // Clear timeout, as mouse is still moving
      clearTimeout(timeout);
    
      // Add class, as mouse is still moving
      document.querySelector('body ').classList.add('change-cursor')
    
      // Schedule class to be removed very shortly in the future
      timeout = setTimeout(function() {
        document.querySelector('body').classList.remove('change-cursor')
      }, 100)
    
    }