JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box" id="the-box">This BOX</div>
<div class="box"></div>
<div class="box"></div>
CSS
.box {
border:2px solid black;
height: 400px;
width: 200px;
margin: 0 auto;
margin-top:10px;
}
JavaScript
// document ready
$(function () {
// define the isOnScreen plugin from http://jsfiddle.net/moagrius/wN7ah/
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft(),
right: win.scrollLeft() + win.width(),
bottom: win.scrollTop() + win.height()
};
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
// define throttling function for use in scroll event listener
// ref: http://blogorama.nerdworks.in/javascriptfunctionthrottlingan/
function throttle(delay, callback) {
var previousCall = new Date().getTime();
return function() {
var time = new Date().getTime();
if ((time - previousCall) >= delay) {
previousCall = time;
callback.apply(null, arguments);
}
};
}
// set up an event to listen for window scroll 4 times a second
$(window).on('scroll', throttle( 250, function () {
// if #the-box is visible the call init functions and disable window scroll
// event listener, as you only want to initialise the lightbox once
if ( $("#the-box").isOnScreen() ) {
// for demo purposes
alert('init');
// call your init functions here
//getThemenCount();
//moveThemenAnimate();
// turn off scroll listener
$(window).off('scroll');
}
}));
});