Set and change color in the menu depending on the scroll

4

Good afternoon I wondered if some way to change the color of a floating menu in a one page template depending on the section of the page where we are. As in this example:

link

But without using Bootstrap because I would like to keep my original menu

    
asked by anonymous 31.07.2015 / 19:28

2 answers

1

Create a CSS class with the color you want and apply the effects you want. Then you have to measure the Scroll and decide from which value to apply this class.

In native JavaScript this would look like this:

(function () {
    var menu = document.getElementById('menu'); // colocar em cache
    window.addEventListener('scroll', function () {
        if (window.scrollY > 0) menu.classList.add('menuFixo'); // > 0 ou outro valor desejado
        else menu.classList.remove('menuFixo');
    });
})();

CSS

.menuFixo {
    position: fixed;
    top: 0px;
    background-color: #ccf;
}

jsFiddle: link

The reason for using (function () { ... })(); is because in this way we can cache the menu element, without exporting to the global space, and save resources since the scroll event is fired many times.

    
31.07.2015 / 22:05
1

You need to use the scroll event of the window object, and the scrollTop to capture position:

$(window).scroll(function() { 
    var scroll = $(window).scrollTop();

    if (scroll > 500) {
        $('.menu').css('background-color','yellow');
    } else {
        $('.menu').css('background-color','blue');
    }
});

Example working on JSFiddle .

    
31.07.2015 / 20:01