Question

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.

Was it helpful?

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

OTHER TIPS

You can try something like this

window.onscroll = function () {
    var top=0;
    var top=document.body.scrollTop;
 if(top < 200){
     $("a[href='#home']").parent().css("background-color","Green");
         $("a[href='#home']").parent().siblings().css("background-color","");
       }

       if((top >= 200) && (top < 800)){
         $("a[href='#Services']").parent().css("background-color","red");
         $("a[href='#Services']").parent().siblings().css("background-color","");
       }    
}

JS Fiddle Demo

Sorry If you don't want to use Jquery. Here I am just giving you an idea to how to achieve that.

Give this a try. Working Demo

window.onscroll = function () {
    var offset = Math.max(document.documentElement.scrollTop, document.body.scrollTop),,
        lis = document.getElementsByTagName('li');

    var colorMap = [
        { value: 200, color : 'green'} ,
        { value: 800, color : 'red' },
        { value: 2800, color: 'purple'}
    ];

        var isColorSet = false;
         for (var i=0; i<colorMap.length; i++) {
             lis[i].style.background='black';
             if (!isColorSet && offset < colorMap[i].value) {
                 lis[i].style.background = colorMap[i].color;
                 isColorSet = true;
             }
        }
}

Let me know if it works for you.

Please find Updated Demo Link here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top