Search code examples
jquerysmooth-scrollingwindow.location

Add window.location to body class


I am trying to put together a smooth scrolling nav that as you are scrolling the entire header encompassing the menu changes background colors to match the defined color of that section. I am using Foundation 6 with the magellan feature for my nav.

I am trying to get my JS to get the current URL and add a class to the body that is the current URL.

var current_location = window.location.href.split('/');
var page = current_location[current_location.length - 1];

This gets me my URL hash (i.e.: #section2, #section3). I need to watch that as it changes on scroll of the page and add those to the body class while removing the previous one after you leave that section.


Solution

  • Went about it a different method, wanted to post it here for reference:

    $(document).scroll(function () {
    
        var headerHeight = $('#header').height() + $('.bottom-header').height() - 4;
    
        var x = $(this).scrollTop(),
            section1 = $('#section1'),
            section2 = $('#section2'),
            section3 = $('#section3'),
            section4 = $('#section4');
            section5 = $('#section51-a');
    
    
        if (x >= section1.offset().top && x < (section1.offset().top + section1.height())) {
            $('.top-header').css("background-color", "#cc00cc");
        }
    
    
        if (x >= (section2.offset().top - headerHeight) && x < (section2.offset().top + section2.height())) {
            $('.top-header').css("background-color", "#009999");
        }
        if (x >= (section3.offset().top - headerHeight) && x < (section3.offset().top + section3.height())) {
    
            $('.top-header').css("background-color", "#ea148c");
        }
        if (x >= (section4.offset().top - headerHeight) && x < (section4.offset().top + section4.height())) {
            $('.top-header').css("background-color", "#999900");
        }
        if (x >= (section5.offset().top - headerHeight) && x < (section5.offset().top + section5.height())) {
            $('.top-header').css("background-color", "#0066cc");
        }
    
    
    });