Run a function constantly

12.5k Views Asked by At

I'm using the excellent inView plugin to check if an element is visible in the viewport, using setInterval, but the function only runs once and only when the element IS visible, not otherwise (should run else statement).

var checkViewport = setInterval(function() {
    $('#colorbox').on('inview', function(event, visible) {
      if (visible) {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);
2

There are 2 best solutions below

0
On BEST ANSWER

Bind the event once, and check a separate variable. Try this:

var isVisible = false;

$('#colorbox').on('inview', function(event, visible) {
    isVisible = visible;
});

var checkViewport = setInterval(function() {
    if (isVisible) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}, 5000);

You can structure this differently to make sure isVisible isn't a global variable and can be accessed by the setInterval still as well.

0
On

The code in your example only binds an event when the element's in the viewport. You're not actually executing anything, just repeatedly binding an event.

I would suggest instead checking the element colorbox every interval, then logging to the console whether the colorbox is visible.

Source (HTML DOM and JavaScript):

var checkViewport = setInterval(function() {
    myColorBox = document.getElementById("colorbox");
      if (myColorBox.style.visibility == "visible") {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);