JSFiddle - React, Tailwind, and code Playground
by Dipak1991
HTML
<div id="red">This RED DIV</div>
<div id="green">This GREEN DIV</div>
<div id="yellow">This YELLOW DIV</div>
CSS
div {
height:500px;
background:red;
text-align:center;
font-size:40px;
}
#green {
background:green;
}
#yellow {
background:yellow;
}
JavaScript
$(function () {
var divs = [],
body = $('body, html'),
currentDiv = 0,
nextDiv = 1,
timeout;
$('div').each(function () {
divs.push($(this));
});
var scrollListen = function () {
$(window).one('scroll', function () {
doScroll($(this).scrollTop());
});
};
var scrollEnd = function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
scrollListen();
}, 10);
};
var doScroll = function (scrollTop) {
var direction = scrollTop - divs[currentDiv].offset().top;
if (direction > 0 && currentDiv + 1 < divs.length) {
nextDiv = currentDiv + 1;
} else if (direction > 0 && currentDiv + 1 >= divs.length) {
nextDiv = 0;
} else if (currentDiv - 1 > -1) {
nextDiv = currentDiv - 1;
} else {
nextDiv = 0;
currentDiv = 1;
}
if (currentDiv === nextDiv) {
scrollEnd();
}
body.animate({
scrollTop: divs[nextDiv].offset().top
}, 1000, function () {
currentDiv = nextDiv;
scrollEnd();
});
};
scrollListen();
});