Categories
JavaScript Answers

How to Make an Anchor Link Go Some Pixels Above Where it’s Linked To with JavaScript?

Spread the love

We can use the window.scrollTo method to scroll to the coordinates we want on the page when we click on a link with a hash as the href .

For instance, we can write the following HTML:

<a href='#'>link 1</a>
<a href='#foo'>link 2</a>
<a href='#bar'>link 3</a>

<div id='bar' style='height: 500px'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

<div id='foo' style='height: 500px'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

Then we write:

const offsetAnchor = () => {
  if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
  }
}

const anchors = document.querySelectorAll('a[href^="#"]')

for (const a of anchors) {
  a.addEventListener('click', (event) => {
    window.setTimeout(() => {
      offsetAnchor();
    }, 0);
  });
}

document.addEventListener('click', (event) => {
  window.setTimeout(() => {
    offsetAnchor();
  }, 0);
});

window.setTimeout(offsetAnchor, 0);

We have the offsetAnchor function that checks if the hash is appended to the URL with location.hash.length .

If it exists, then we scroll to the location of the element with the ID given by the hash, but with the y coordinate subtracted by 100.

Next, we get the a elements with href starting with the pound sign.

And if the for-of loop, we call addEventListener to add a click handler to each a element.

In the click handler, we call offsetAnchor in the setTimeout callback.

We put it in the setTimeout callback so that it’ll be called after the scrolling is done.

Next, we do the same with document so we scroll 100 pixels up from where we click on the page.

Also, we call offsetAnchor initially to scroll to the initial coordinates of the page.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *