Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda