Key Scroll

by David Nabb

HTML

<script src="https://jeremyckahn.github.io/keydrown/dist/keydrown.min.js"></script>
<div style="white-space: nowrap" id="placeholder">
  <section class="active" id="section1">
    <img src="http://placehold.it/500x500/aaafff" />
  </section>
  <section id="section1">
    <img src="http://placehold.it/500x500/fffaaa" />
  </section>
  <section id="section2">
    <img src="http://placehold.it/500x500/bbbccc" />
  </section>
  <section id="section3">
    <img src="http://placehold.it/500x500/ccceee" />
  </section>
  <section id="section4">
    <img src="http://placehold.it/500x500/aaaddd" />
  </section>
  <section id="section5">
    <img src="http://placehold.it/500x500/dddeee" />
  </section>
  <section id="section6">
    <img src="http://placehold.it/500x500/fffedc" />
  </section>
</div>

CSS

body {
  min-height: 2000px;
}

section {
  height: 100vh;
}

img {
  height: 100%;
  display: block;
}

JavaScript

$.fn.isInViewport = function() {
	"use strict";
	var elementTop = $(this).offset().top;
	var elementBottom = elementTop + $(this).outerHeight();
	var viewportTop = $(window).scrollTop();
	var viewportBottom = viewportTop + $(window).height();
	return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
	"use strict";
	$("section").each(function() {
	  if ($(this).isInViewport()) {
      $(this).addClass("active");
		} else {
      $(this).removeClass("active");
		}
	});
});
kd.run(function () {
  kd.tick();
});
kd.DOWN.up(function (e) {
  var $targetElement;
  $targetElement = $('.active').next('section');
  if (!$targetElement.length) return;

  //scroll element into view    
  $('html, body').clearQueue().animate({
    scrollTop: $targetElement.offset().top
  }, 500);
});
kd.UP.up(function (e) {
  var $targetElement;
  $targetElement = $('.active').next('section').prev('section');
  if (!$targetElement.length) return;

  //scroll element into view    
  $('html, body').clearQueue().animate({
    scrollTop: $targetElement.offset().top
  }, 500);
});