Elia Weiss
Elia Weiss

Reputation: 9915

jQuery window in/out of view handler

I want to stop the animation on an HTML page once it is out of view

I tried to use

$(window).focus(function () {
    // start animation
}).blur(function () {
    // stop animation
});

but this code also stops the animation if it is the background of another window.

Is there an handler for window in/out of view in JS or jQuery?

i.e. something like:

$(window).windowInView(function () {
    // start animation
}).windowOutView(function () {
    // stop animation
});

Upvotes: 0

Views: 49

Answers (1)

Sven Liivak
Sven Liivak

Reputation: 1413

There's two ways: window.requestAnimationFrame()

example taken/modified from linked page

<div id="rec" style="width: 5px; height: 5px; background: black;"></div>

var start = null;
var left=false;
var element = document.getElementById('rec');
element.style.position = 'absolute';

function step(timestamp) {
  if (!start) start = timestamp;
  if(!left){
      var progress = timestamp - start;
      element.style.left = Math.min(progress / 10, 600) + 'px';
      if (progress < 6000) {
        window.requestAnimationFrame(step);
      }else{
        start = timestamp;
        left = true;
        window.requestAnimationFrame(step);
    }
  }else{
     var progress = (start+6000)-timestamp;
      element.style.left = Math.max(progress / 10, 0) + 'px';
     if (progress > 0) {
        window.requestAnimationFrame(step);
     }else{
        start = timestamp;
        left=false;
        window.requestAnimationFrame(step);
     }
  }
}

or Page Visibility API

document.addEventListener("visibilitychange", function(){
    if (document.hidden) {
        console.log('hidden');
    }else{
        console.log('visible');
    }}, false);

Upvotes: 1

Related Questions