JSFiddle - React, Tailwind, and code Playground
by drawcard
HTML
<script src="//cdn.jsdelivr.net/jquery.waypoints/2.0.4/waypoints.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<section id="one" class="pink">Scroll down...</section>
<section id="two" class="yellow">1</section>
<section id="three" class="green">2</section>
<section id="four" class="purple">3</section>
<section id="five" class="orange">4</section>
CSS
body {
background: #33333d;
margin:0; padding:0;
}
section {
width: 100%;
height: 100vh;
padding:60px;
}
.pink {
background: pink;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
.purple {
background: purple;
}
.orange {
background: orange;
}
JavaScript
function snapScroll(){
$('section').each(function(){
var currentSection = $(this);
isScrolledIntoView(currentSection);
})
}
var lazyLayout = _.debounce(snapScroll, 1200);
$(window).scroll(lazyLayout);
function isScrolledIntoView(elem)
{
var currentSection = elem;
var windowHeight = $(window).height();
var windowTop = $(document).scrollTop();
var windowBottom = windowTop + $(window).height();
var sectionHeight = currentSection.height();
var sectionTop = currentSection.offset().top;
var sectionBottom = sectionTop + sectionHeight;
if ((sectionTop <= windowTop + (windowHeight / 2) ) && (sectionTop >= windowTop)) {
$('html, body').stop().animate({
scrollTop: sectionTop
}, 400);
window.location.hash = currentSection.attr('id');
currentSection.addClass('active');
}
else if ((sectionBottom >= windowTop + (windowHeight / 2)) && (sectionBottom <= windowBottom)) {
$('html, body').stop().animate({
scrollTop: sectionBottom - windowHeight
}, 400);
window.location.hash = currentSection.attr('id');
currentSection.addClass('active');
}
else {
currentSection.removeClass('active');
}
}
function scroll(windowTop,sectionTop,windowBottom,sectionBottom){
if ((windowTop > sectionTop) && (windowBottom < sectionBottom)){
console.log('do nothing');
}
else {
$('html, body').stop().animate({
scrollTop: sectionTop
}, 400);
}
}