1

I am writing a simple infinite counter in JavaScript when the page loads it starts counting.

I would like to stop the counter when the mouse pointer is outside of the viewport.

Please help?

<script type="text/javascript">
                    
        var i=0;
                        
            setInterval(function (){
               i++;
              
               document.getElementById("counterLoop").innerHTML=i;
               
            },1000);
          
    var viewportWidth  = document.documentElement.clientWidth;
     var viewportHeight = document.documentElement.clientHeight;

     
     function getCursorXY(e) {   
CurX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

}

How can I capture mouse move event outside of the viewport width and height?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
pavan
  • 334
  • 6
  • 20

2 Answers2

6
jQuery(document).mouseleave(function(){console.log('out')})

this will trigger when ever the mouse is not in your page as you want. just change the function to do what every you want .

and also you may use :

jQuery(document).mouseenter(function(){console.log('in')});

to trigger when the mouse enters the page to start your counter again.

Hilmi
  • 3,411
  • 6
  • 27
  • 55
  • This technique is not stable in Chrome 15 to 56 (my current version). But it works very will in Firefox. See: http://stackoverflow.com/questions/7448468/why-cant-i-reliably-capture-a-mouseout-event – Tremours Mar 07 '17 at 01:01
0

Below code is works for me,

const body = document.getElementsByTagName('body')[0];
var intervalExec;
body.addEventListener('mouseenter', function() { //mouseover, mousedown, mousemove
   // Write your setInterval execution
   intervalExec = setInterval(updateCounter, 1000); // updateCounter is your executable function
});
body.addEventListener('mouseleave', function() { //mouseout, mouseup
   clearInterval(intervalExec);
});
Muthulakshmi M
  • 651
  • 7
  • 8