JSFiddle - React, Tailwind, and code Playground

by bartek

HTML

<section id="Section1"></section>
<section id="Section2"></section>
<section id="Section3"></section>

CSS

section {
    width: 100%;
    height: 343px;
    position: relative;
}
#Section1 {
    background: red;
}
#Section2 {
    background: blue;
}
#Section3 {
    background: orange;
}

JavaScript

$(document).keydown(function (event) {
    console.log(event.keyCode);
    if (event.keyCode == 38) {
        event.preventDefault();
        scrollToPrevious();
    } else if (event.keyCode == 40) {
        event.preventDefault();
        scrollToNext();
    }
});

function scrollToPrevious() {
    var prevElement = getCurrentlyVisibleSection().prevAll('section');
    if (prevElement.length > 0) scrollToElement(prevElement);
}

function scrollToNext() {
    var nextElement = getCurrentlyVisibleSection().nextAll('section');
    if (nextElement.length > 0) scrollToElement(nextElement);
}

function scrollToElement(ctrl) {
    $('html, body').animate({
        scrollTop: ctrl.offset().top
    }, 200);
}

function getCurrentlyVisibleSection() {
    $("#Section1").visible(true);
    var rtn;
    $.each($('section'), function (ind, val) {
        if ($(this).visible(false)) {
            //true here means ALL the element has to be visible.. change to False if you want ANY Part of the item to be visible.. 
            rtn = $(this);
        }
    });
    return rtn;
}

(function ($) {
    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function (partial, hidden, direction) {

        if (this.length < 1) return;

        var $t = this.length > 1 ? this.eq(0) : this,
            t = $t.get(0),
            vpWidth = $w.width(),
            vpHeight = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function') {

            // Use this native browser method, if...