最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting Mouse Movement Without JQuery - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Nov 3, 2012 at 4:46 mark cassadaymark cassaday 1531 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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);
(function(){
   var moved = false
   window.onmousemove = function(e){
      if(!moved){
          moved = true;
          // do what you want after mousemove, here
      }
   }
})()
发布评论

评论列表(0)

  1. 暂无评论