Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Mouse Movement Without JQuery

I'm looking for a small piece of javascript that will check for mouse movement and in the event it does execute a function. I'm looking to do this without jquery and preferably compatible with most modern browsers. I have this small script which detects when the mouse isn't moving:

<script>
document.onmousemove = (function() {
  var onmousestop = function() {
    /* do stuff */
  }, thread;

  return function() {
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 500);
  };
})();
</script>

I'm hoping things can be edited into firing the do stuff when the mouse is moved for the first time after loading the script? Any help? Thanks

like image 464
mark cassaday Avatar asked Nov 03 '12 04:11

mark cassaday


People also ask

Can website detect mouse movement?

JavaScript is implemented as part of a Web browser and is supported by all the major web browsers, including Internet Explorer, Firefox and Safari. Therefore, using this language, Web developers can track user's mouse movements simply by entering lines of code on a page.

How do I get current mouse position?

To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console.

What is mousemove event?

The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.

How do you check if the mouse is over an element?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.


1 Answers

The problem with Amit's solution is that it removes any existing mousemove listeners. Also, it doesn't clean up when the mouse is first moved, and thus creates unnecessary overhead.

This is the clean way of doing it:

var myListener = function () {
    document.removeEventListener('mousemove', myListener, false);
    // do stuff
};

document.addEventListener('mousemove', myListener, false);

See it in action: http://jsfiddle.net/JQBmA/

If you need to support older IEs, you can use this:

var addListener, removeListener;
if (document.addEventListener) {
    addListener = function (el, evt, f) { return el.addEventListener(evt, f, false); };
    removeListener = function (el, evt, f) { return el.removeEventListener(evt, f, false); };
} else {
    addListener = function (el, evt, f) { return el.attachEvent('on' + evt, f); };
    removeListener = function (el, evt, f) { return el.detachEvent('on' + evt, f); };
}

var myListener = function () {
    removeListener(document, 'mousemove', myListener);
    // do stuff
};

addListener(document, 'mousemove', myListener);
like image 126
user123444555621 Avatar answered Oct 24 '22 14:10

user123444555621