Friday, May 13, 2016

Highlight menu items based on anchors

Use the following js:
$(window).scroll(function(){
    var scrollTop = $(document).scrollTop();
    var anchors = $('body').find('h1');
    
    for (var i = 0; i < anchors.length; i++){
        if (scrollTop > $(anchors[i]).offset().top - 50 && scrollTop < $(anchors[i]).offset().top + $(anchors[i]).height() - 50) {
            $('nav ul li a[href="#' + $(anchors[i]).attr('id') + '"]').addClass('active');
        } else {
            $('nav ul li a[href="#' + $(anchors[i]).attr('id') + '"]').removeClass('active');
        }
    }
});
Where: H1: holds the anchor ID
nav ul li a: shows how to get to the menu items

Updated Code (function):

  function activeMenus(anchor, menuItem){
    //keeps search menu item active on load -- OPTIONAL
    $(menuItem + '[href="#content"]').addClass('active');
    $(window).scroll(function(){
        var scrollTop = $(document).scrollTop();
        var anchors = $('body').find(anchor);

        for (var i = 0; i < anchors.length; i++){
            if (scrollTop > $(anchors[i]).offset().top - 190 && scrollTop < $(anchors[i]).offset().top + $(anchors[i]).height() - 190) {
                $(menuItem + '[href="#' + $(anchors[i]).attr('id') + '"]').addClass('active');
            } else {
              if($('#sticky-index ul li a.active').length > 2) {
                  $(menuItem + '[href="#' + $(anchors[i]).attr('id') + '"]').removeClass('active');
              }
            }
        }

    });
  }
Usage:
activeMenus('.paragraph-row', '#sticky-index ul li a');

No comments:

Post a Comment