Skip to content

Instantly share code, notes, and snippets.

@erickolivares
Created September 12, 2017 06:33
  • Select an option

Select an option

Revisions

  1. erickolivares created this gist Sep 12, 2017.
    54 changes: 54 additions & 0 deletions Active Nav tabs, activated on scroll
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    jQuery(document).ready(function( $ ) {

    var modId = $(".main-content .row > div"); //divs with ID's
    var navItems = $(".custom-nav li"); //nav items li

    var points = [];

    for (var i = 0; i < modId.length; i++) {
    var thismod = modId.eq([i]);
    var thismodID = thismod.attr("id")
    for (var j = 0; j < navItems.length; j++) {
    var thisnavhref = navItems.find('a').eq([j]).attr("href").slice(1);
    var thisnavlink = navItems.find('a').eq([j]);
    if(thismodID == thisnavhref) {
    points.push([[j],thismod.offset().top]);
    }
    }
    }

    function lookup(location) {

    var offset = $(window).height() - 200;
    var activeLocation = offset + location;

    for (var x = 0; x < points.length; x++) {

    var nextItem = x + 1;

    if( points[x] === 0) {
    var currectItemValue = 0;
    } else {
    var currectItemValue = points[x][1];
    }

    if(points.length + 1 === nextItem + 1) {
    var nextItemValue = 100000;
    } else {
    var nextItemValue = points[nextItem][1];
    }

    if(currectItemValue < activeLocation && activeLocation < nextItemValue) {
    navItems.find('a').eq(points[x][0]).addClass('active');
    } else {
    navItems.find('a').eq(points[x][0]).removeClass('active');
    }
    }
    };

    window.onscroll = function() {
    var currentpos = $(document).scrollTop();
    lookup(currentpos);
    };

    });