Skip to content Skip to sidebar Skip to footer

Adding A Css Class Based On Browser Scroll Position With Jquery - Looking For A More Modular Approach

On my current site(uptrde.com) I have it setup to when you scroll to a certain section of the page the nav a that corresponds with that section lights up. However, I feel that the

Solution 1:

Here's what I'd recommend. Loop through each of the sections on the page and get the rendered height. Add each of those heights to an array, and then loop through the array when you are adding the classes. Something like this:

$(window).scroll(function(){
     var scroll = $(window).scrollTop();
     var section_height = newArray();
     var section_position = newArray();
    $('.main-container').children().each(function(){
        section_height.push($(this).height());
        section_position.push($(this).offset().top);
    });

    for(i=0; i<section_position.length; i++){
        if($(window).scrollTop() > section_position[i] - (section_height[i] / 4)){
            $('.mainNav li').not(':nth-child('+i+')').find('a').removeClass('selected');
            $('.mainNav li:nth-child('+i+') a').addClass('selected');
        } else {
            $('.mainNav li:nth-child('+i+') a').removeClass('selected');
        }
    }
});

I haven't tested this with your site, but I used the same code on another site earlier today, and it worked like a charm. You'll want to play with the calculation used in the if statement in the for loop. I have it set to change to the next section when you're about 1/4 of the height away from it. In other words, I wanted it to change to the next nav element when you were "almost" to it in the scroll position. I didn't want to have to wait till it was all the way at the top of your screen before changing the highlighted nav element. You, however, may choose to do it differently.

Solution 2:

maybe this can help you

$(function() {
    $(window).scroll(function() {
        var scroll = $(window).scrollTop() + 90;
        var currentArea = $('.area').filter(function() {
            return scroll <= $(this).offset().top + $(this).height();
        });
        $('nav a').removeClass('selected');
        $('nav a[href=#' + currentArea.attr('id') +']').addClass('selected');
        //console.debug('nav a[href=#' + currentArea.attr('id') +']');
    });
});

JSFiddle: http://jsfiddle.net/LGzxq/1/

Post a Comment for "Adding A Css Class Based On Browser Scroll Position With Jquery - Looking For A More Modular Approach"