How to modify an item at a specific point on the page? (HTML, CSS)

Asked

Viewed 941 times

1

Hello, on my page has a fixed menu composed by text, I need that when it reaches a certain point of the page it changes from white to black but I have no idea how I can do it.

Site

  • How to define what is the "certain point"?

  • but who was white and should be black? How to create a Minimum, Complete and Verifiable https://answall.com/help/mcveexample

  • Post code as image - https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-ask-questions/5485#5485

  • what would be "certain point"? to change the style of an element in JS, uses elemento.style = "estilo"; that’s it?

2 answers

1


Does it need to be CSS only?

If it can be with Javascript can use the scroll touchmove of jQuery.

Follow 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ão muda.</div>
<div>Não muda.</div>
<div>Não muda.</div>
<div id="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 function scroll touchmove is that you don’t need set the size of the scroll that will be made to change the property of the element, because the size of the scroll may change depending on the device that is accessing the site. Then the scroll touchmove only changes the property when the top of the browser arrives in the element chosen that in the case of my code was the <div> with the id="mudar".

I learned from the guy who answered that question of mine: Change appearance when passing through Section

1

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

Browser other questions tagged

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