Change navigation active class on window scroll

前端 未结 5 1417
心在旅途
心在旅途 2020-12-28 11:31

i want to create a scroll effect like here http://www.strikingly.com/s/pages/default-ion?demo=ion#1 All i need for this moment is to change navigation li class active when

5条回答
  •  半阙折子戏
    2020-12-28 12:16

    I know I am late, but my answer may help the new viewers of this thread. Tushar Gupta's answer is correct. But if there a link in menu that is redirecting to any other page. Tushar Gupta's Answer will throw an error. For Example

        
       

    This will throw an error in console like this. And scrolling will not work for Contact. I Updated Tushar's code to fix that issue.

    function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#menu-center a[href*=#]:not([href=#])').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active"); //added to remove active class from all a elements
            currLink.addClass("active");
        }
        else{
            currLink.removeClass("active");
        }
    });
    }
    

提交回复
热议问题