Home > database >  JavaScript scoll then highlight
JavaScript scoll then highlight

Time:10-28

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?

CodePudding user response:

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);
  
});
  • Related