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

177
Visualizações
JavaScript scoll then highlight

In my webpage, using JavaScript, I would like to first scroll the div and then highlight an object in the div.

This is code I am using and it is fully working, however, I would like to avoid timeout.

  let commentDiv = document.getElementById('commentsDiv'); 
  commentDiv.scrollTop =  scrollValue;

  setTimeout(function(){decorateMarker(markerObj);}, 500);

I changed my code to use promise, but it doesn't work. decorateMarker(markerObj) runs, but the comment object is not highlighted unless I add setTimeout around.

let myPromise = new Promise(function(myResolve, myReject) {
  commentDiv.scrollTo(0,scrollValue);
  myResolve(markerObj); 
});

myPromise.then(
  function(markerObj) { 
    //highlight comment 
    decorateMarker(markerObj);
  }
)

Any suggestion on how to ensure scrolling is fully finished before highlighting code runs?

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

0

One way you can achieve this is to attach a scroll listener when the scrollTo is called. Then remove the listener once the desired location is reached. This way you can ensure that the highlight occurs only when the desired scroll position is reached.

I've created a very simple implementation of this as an example:

Codepen Example

let button = document.getElementById("scrollToElem");

button.addEventListener('click', () => {
  window.scrollTo({top: 2000, behavior: "smooth"}); 
  
  scrollHandler = () => {    
    if(this.scrollY === 2000){
      console.log('remove scroll listener');
      document.removeEventListener('scroll', scrollHandler, true);
      //Now do your highlight.
    }
    
  }
  
  document.addEventListener('scroll', scrollHandler, true);
  
});
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