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:
But without using Bootstrap because I would like to keep my original menu
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:
But without using Bootstrap because I would like to keep my original menu
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;
}
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.
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 .