Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
Add/remove class to element after scrolled x pixels

I would like to add a class to an element after being X pixels away from the top of the page and remove that class if you get closer to the top. For that I created the following code

document.getElementsByTagName("body")[0].onscroll = function() {
function offset(el) {
    var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}

var filter = document.querySelector('.filter-component.navbar');
var divOffset = offset(filter);
console.log(divOffset.left, divOffset.top);

var hereitsfixed = divOffset.top + 55;


    if (this.scrollTop >= hereitsfixed) {
        filter.classList.add("lol");
} else  {
        filter.classList.remove("lol");
    }
};

So first I am trying to find out how far the element is away from the top (cause that could change) and add 55 pixels to that. I get the correct number here. And then when you scroll down and are that number away from the top or more, it should add the class or remove it. But nothing happens here. Not even an error message. I only get the console.log number (which is alright, I remove it later).

What am I doing wrong here? Can't figure it out.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda