Hello, my page has a fixed menu consisting of text, I need it when it reaches a certain point on the page it changes from white to black but I have no idea how I can do it.
Does it have to be only with CSS?
If it can be with JavaScript you can use jQuery scroll touchmove .
Here's an example:
$(window).on("scroll touchmove", function() {
if ($(document).scrollTop() >= $("#mudar").position().top) {
$('body').css('background-color', 'orange');
} else {
$('body').css('background-color', 'white');
}
});
div{
height: 300px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><div>Nãomuda.</div><div>Nãomuda.</div><div>Nãomuda.</div><divid="mudar">Mudar quando chegar aqui.</div>
<div>Não muda.</div>
<div>Não muda.</div>
<div>Não muda.</div>
<div>Não muda.</div>
<div>Não muda.</div>
<div>Não muda.</div>
The advantage of this scroll touchmove function is that you do not need set the size of the scroll that will be made to change the element property, because the size of the scroll may change depending on the device that is accessing the site. So the scroll touchmove only change the property when the top of the browser arrives at the element chosen that in the case of my code it was
<div>
withid="mudar"
.
I learned from the guy who answered this question of mine: Change appearance by going through the section
You can use both jQuery and Javascript.
JavaScript
window.addEventListener('scroll', myFunction);
function myFunction() {
// Seleciona o elemento alvo
var element = document.querySelector(".element");
if (window.pageYOffset > 100) {
// Ao descer 100px, realiza as modificações desejadas
element.classList.add('scrolled');
} else {
// Ao retornar ao topo da página, desfaz as modificações
element.classList.remove('scrolled');
}
}
jQuery
$(window).scroll(function(e){
if ($(this).scrollTop() > 100) {
// Ao descer 100px, realiza as modificações desejadas
$('.element').addClass('scrolled');
} else {
// Ao retornar ao topo da página, desfaz as modificações
$('.element').removeClass('scrolled');
}
});
Examples