Fix and change color in menu depending on scroll

Asked

Viewed 6,866 times

5

Good afternoon I would like to know if there is any 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:

http://ironsummitmedia.github.io/startbootstrap-creative/

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

2 answers

2

You need to use the event scroll of the object window, and the method scrollTop to capture the 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.

2


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 what value to apply that class.

In native Javascript this would be 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: http://jsfiddle.net/k343a9fb/

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.