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

156
Visualizações
how to highlight navigation bar while scrolling

I have this basic HTML code which has sections, and then I created a basic navigation bar dynamically by javaScript

function buildNav() {
    for (section of sections) {
        let item = document.createElement("li");

        item.innerHTML = `<a data-nav="${section.id}">${section.dataset.nav}</a>`;
        item.classList.add("item");
}
        navBar.appendChild(item);
        
    }
}

and I used this function to add active class to each section

function isInView(element) {
    const rect = element.getBoundingClientRect();
    return rect.top >= -70 && rect.top <= 300;
};

function addActive() {
    document.addEventListener(
        "scroll",
        () => {

            for (section of sections) {
                if(isInView(section)){
                    section.classList.add('active')
                }else{section.classList.remove('active')}
             };
            })
            }

my question is how can I highlight the item at the navigation bar that represents the section in view

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should apply active class to only the item that matches the current section of the page. Try this: -

function isInView(element) {
    const rect = element.getBoundingClientRect();
    if(rect.top > 70 && rect.top < 150){            //Assumed Y-offset for 1st section
        return element.id          //Assuming it returns 1 for 1st element
    }
    else if(rect.top > 150){
        return element.id          //Returns 2 for 2nd element
    }
   
};

function addActive() {
    document.addEventListener(
        "scroll",
        () => {

            for (section of sections) {
                if(isInView(section) == section.id){
                    section.classList.add('active')    //Only apply active class to this section
                }
                else{
                    section.classList.remove('active')  //Remove the active class from all other sections
                }
            };
               
            
            })
            }
about 4 years ago · Juan Pablo Isaza Relatório
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