lewis
lewis

Reputation: 89

Change active tab depending on scroll position

I'm currently messing around with trying to create a one page website. At the moment I've got the navigation menu to scroll to the selected part of the website when clicked and active tab will change on click too. But what I'm trying to figure out is how to make the css change to the active tab when the next page has been scrolled on to (and not clicked in the menu).

$(document).ready(function(){
    $("nav ul li").click(function(){
        var sectionClass = $(this).attr('class');   
            if ($(this).hasClass('active')){
            }
            else {
                $("nav ul li.active").removeClass('active');    
                $(this).addClass('active');                                 
                sectionId = $(this).attr('id');
                var parts = sectionId.split("_");
                $('html, body').animate({                                       
                    scrollTop: $("#" + parts[1]).offset().top
                }, 'slow');
            }
        });
    });
<body>
    <nav class="nav-bar">
        <ul>
            <li class="active" id="menu_index">Welcome</li>
            <li id="menu_page1">Menu1</li>
            <li id="menu_page2">Menu2</li>
            <li id="menu_page3">Menu3</li>
            <li id="menu_page4">Menu4</li>
        </ul>
    </nav>
    <div id="index"></div>
    <div id="page1"></div>
    <div id="page2"></div>
    <div id="page3"></div>
    <div id="page4"></div>
</body>

https://jsfiddle.net/nsefqo3w/

Added jsfiddle to show how it is just now, I'm new so you'll probably spot a few problems!

Upvotes: 2

Views: 16495

Answers (1)

Ole Haugset
Ole Haugset

Reputation: 3797

Change your menu to be setup like this:

<ul>
     <li><a href="#page1">Page 1</a>
     ...
</ul>

This way it scrolls to the DOM element with an id of page1 when the anchor is clicked.

Then you can use the following code to mark as active on scroll:

function onScroll(event){
var scrollPos = $(document).scrollTop();
$('li>a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('li>a.active').removeClass("active");
        currLink.addClass("active");
    }
    else{
        currLink.removeClass("active");
    }
});
}
$(document).ready(function () {
    $(document).on("scroll", onScroll);
});

EDIT:

Use your own jQuery code so that it changes to active on onclick as well.

Source: http://jsfiddle.net/cse_tushar/Dxtyu/141/

Upvotes: 7

Related Questions