Search code examples
javascriptonscroll

Nav background color changes upon scroll


I want part of my navigation background to change color to match the content color as the user scrolls down.

An exact example of this is available at blobfolio.com.

My attempt:

window.onscroll = function () {
    var background = document.body.scrollTop < 200 ? '#fff' : 'red',
        elems = document.getElementsByTagName('nav');

    for (var i=0; i<elems.length; i++) {
        elems[i].style.background = background;
    }
} 

I think that it will include for loops. I have tried in this JSFiddle but the entire background changes, which isn't what I want.

I am really quite stuck, any help would be much appreciated!

Also I am trying to do this in pure JavaScript - no frameworks.


Solution

  • I think this does what you're asking for:

    window.onscroll = function () {
        var i = 0;
        var elements = document.getElementsByClassName("container");
        for(var j=elements.length-1; j>0; j--)
        {
            if (parseInt(elements[j].getBoundingClientRect().top) <= 0)
            {
                i = j;
                break;
            }
        }
    
        var nav = document.getElementsByClassName("nav");
        for (var j=0; j<nav.length; j++)
            nav[j].style.backgroundColor = "";
    
        nav[i].style.backgroundColor = window.getComputedStyle(elements[i]).getPropertyValue("background-color");
    }
    
    window.onscroll();
    

    Here's a demo on JSFiddle.

    Doing it in pure JavaScript was quite fun :D