JSFiddle - React, Tailwind, and code Playground
HTML
<section id="section1">
</section>
<section id="section2">
</section>
<section id="section3">
</section>
CSS
section {
height: 100%;
}
#section1 {
background-color: red;
}
#section2 {
background-color: blue;
}
JavaScript
/* helpers */
// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom - 25 <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
function anyOfElementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
/* START */
// step 1: get all sections and set viewport height for consistency
var $sections = $('section');
$sections.css('height', window.innerHeight);
// step 2: get current section
var $currSection = $.grep($sections, function($s) {
return isElementInViewport($s);
});
if($currSection.length > 0) {
$(window).scroll(function(){
// step 3. check for any section that is 'partially in viewport'
var $nextAndCurrSection = $.grep($sections, function($s) {
return anyOfElementInViewport($s);
});
if($nextAndCurrSection.length > 0) {
// remove currSection from list
var $nextSection = $($nextAndCurrSection).not($($currSection));
if($nextSection.length > 0) {
alert('test');
}
}
});
}