简体   繁体   中英

Track “OnMouseNotMoving” event in jQuery?

So I was thinking of annoying users of a page a little bit: when user is not moving a mouse, it should display a layer at mouse position, and also hide it when mouse moves, with a delay.

I have delay part figured out using jQuery's delay(). But I'm not sure what would be the best way to implement OnMouseNotMoving.

Is there a 'timer' in jQuery, ie something that would start when mouse doesn't move, and that would fire an event after enough time passes?

Thx.

On mousemove you can add use the setTimeout() and clearTimeout() methods. Something like this:

    var timeout = null;

    $(document).bind('mousemove', function(e) {
        // use e.pageX and e.pageY to position your message

        // clear and set timeout
        if(timeout) {
            hideMessage();
            clearTimeout(timeout);
        }
        timeout = setTimeout(function(x, y){
            return showMessage(x, y);
        }(e.pageX, e.pageY), 3000);

        function showMessage(x, y) {
            // your code to show message
        }
        function hideMessage() {

        }
    });

You have to create this event yourself. Javascript itself has timers. setInterval() is the method you are looking for. It will execute a function at a specified interval.

You basicly check the mouse coordinates if they have not moved for a specified interval, and then do your thing.

Not so far as i know, but why not create an interval that gets the mouse position and check if it's changed:

var x, y, time, mouseTimeout = 2000;

function checkPosition(e) {
  var t = new Date();
  if (e.clientX !== x || e.clientY !== y) {
    //mouse changed
    time = t;
    x = e.clientX;
    y = e.clientY;
  }
  if ((t - time) > mouseTimeout) {
    //annoy users
  }
}

<body onmousemove="checkPosition();">
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM