Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute Jquery when the mouse stops moving

I have a quick script that has a trail follow the cursor:

jQuery(document).ready(function(){
   $(document).mousemove(function(e){
       $('.fall').each(function(){
           if ($(this).css("opacity") == 0){
               $(this).remove();
           };
       });
       t = (e.pageY - 10).toString() + 'px';
       l = (e.pageX - 10).toString() + 'px';
       $('.fall').css("margin_left",l);
       $('.fall').css("margin_top",t);
       var doit = '<div class="fall" style="position:fixed;margin-left:' + l + ';margin-top:' + t + ';">+</div>'
       $('body').prepend(doit);
      $('#status2').html(e.pageX +', '+ e.pageY);

       $('.fall').animate({
           marginTop: '+=50px',
           opacity: 0
       },1000);       
   }); 
});

Now I would like to remove the animate part and have something like the following when the mouse is not moving:

$('.fall').each(function(){
    $(this).fadeOut('slow');
    $(this).remove()
});

I just can't figure out how to execute this when the mouse is not moving for more than like a second. Any ideas?

Thanks, and here is a jsfiddle

like image 244
Ryan Saxe Avatar asked Jun 22 '13 15:06

Ryan Saxe


2 Answers

is this what you require? jsFiddle

lastTimeMouseMoved = new Date().getTime();
var t = setTimeout(function() {
  var currentTime = new Date().getTime();
  if (currentTime - lastTimeMouseMoved > 1000) {
    $('.fall').fadeOut('slow');
    // $('.fall').remove();
  }
}, 1000)
like image 74
Varun Avatar answered Oct 11 '22 08:10

Varun


You add a timeout that fires after one second of inactivity, and clear the timeout if the mouse moves within 1 second etc :

var timer;
$(document).on('mousemove', function(e){
   clearTimeout(timer);

   timer = setTimeout(function() {
       $('.fall').fadeOut('slow', function() {
           $(this).remove();
       });
   }, 1000);
});

FIDDLE

EDIT:

Here's how I'd do it

FIDDLE

like image 45
adeneo Avatar answered Oct 11 '22 08:10

adeneo