[Vuejs]-How to "re-activate" a link once the user scrolls away from an anchor section?

0👍

Whatever your scrolling object is (likely window), you should add an event listener to handle scroll events:

window.addEventListener('scroll', scrollHandler, false);

Your scrollhandler function should check whether there is a hash on the current window location, and if so, check whether the associated element is out of range, and if so, clear the hash.

I can’t use the real location hash or window in a snippet, but this is kind of what you would want to do.

let hash = '#second';
const scrollingEl = document.querySelector('.scrollingArea');

function handleScrollEvent() {
  if (hash) {
    const winY = scrollingEl.scrollTop;
    const hashElY = document.querySelector(hash).getBoundingClientRect().top;
    
    if (hashElY < 0 || hashElY > winY + scrollingEl.height) {
      hash = '';
    }
    console.log(winY, hashElY);
  }
}

scrollingEl.addEventListener('scroll', handleScrollEvent, false);
.scrollingArea {
  height: 400px;
  overflow-y: scroll;
}

.scrollingArea>div {
  height: 250px;
}
<div class="scrollingArea">
  <div id="first">First</div>
  <div id="second">Second</div>
  <div id="third">Third</div>
  <div id="fourth">Fourth</div>
</div>

Leave a comment