0

Given a div box, suppose we want to show a tooltip if the mouse is static inside for a while, showing the tooltips under the mouse cursor, once the mouse moved, the tooltip will disappear.

I want to know is there any way to simulate this? As we know, mouseover is triggered only when enter the box.

Jiaxiang
  • 31
  • 5
  • Use `mousemove` and a `setTimeout`. Clear the timeout / start the timeout over everytime the mouse moves. And in the timeout you do what you have to do. – putvande Aug 14 '14 at 09:28
  • The usual trick is to start a timeout (say 200ms) when the mouse enters the div, and cancel it if the mouse moves outside before the timeout fires. – Salman A Aug 14 '14 at 09:29

1 Answers1

0

As mentioned, add an eventlistener to the document that listens for a mousemove. In that event do a setTimeout that gets cleared / starts over everytime you move the mouse. If the setTimeout runs, it means the mouse hasn't moved for x seconds.

var t;
document.addEventListener('mousemove', function() {
    if (t) clearTimeout(t);
    t = setTimeout(function() {
        alert('mouse hasn\'t moved for 5 seconds');
    }, 5000);
});

Fiddle

putvande
  • 15,068
  • 3
  • 34
  • 50
  • I wouldn't use mousemove: 1. showing the tooltip would require the user to stay absolutely still, which is usually not the case, and 2. it would evaluate on **every** mousemove, and that's just a waste of resources... – Noy Aug 14 '14 at 09:35
  • 1: That is what OP wants. 2: I agree, could have been better. – putvande Aug 14 '14 at 09:37
  • Yes, continuously trigger the mousemove will cause performance issue. – Jiaxiang Aug 15 '14 at 01:48