Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!