Categories
JavaScript Answers

How to Jump to an Anchor Element by Using JavaScript?

Spread the love

We can use the location.href property to get the URL without the hash.

Then we can append the hash to it.

And then we can remove the hash from the URL in the URL bar with history.replaceState .

For instance, we can write the following HTML:

<button>
  jump
</button>
<div id='a'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dignissim lacus, ac ullamcorper ex aliquam vel. Donec nec luctus augue, sit amet porttitor diam. Ut sit amet mi ac risus congue ultricies. Donec et condimentum nisi, sit amet consequat felis. Nam velit nibh, blandit non nunc eget, ullamcorper suscipit ex.
</div>
<div id='b'>
  Phasellus faucibus fringilla ullamcorper. Vivamus gravida urna vel odio rutrum rutrum. Vivamus pretium, orci eget cursus tempus, quam elit rutrum est, vel fermentum sapien odio sit amet velit. Etiam cursus pulvinar massa, non maximus dolor vestibulum id. Morbi mi mauris, iaculis ac sem a, porta vehicula risus. Curabitur tincidunt sollicitudin sapien, ac tristique ligula ullamcorper eget. Donec tincidunt orci non ligula auctor ullamcorper. Aliquam mattis elit mauris, at posuere nulla lobortis id.
</div>

Then we can add a button to scroll down to the div with ID b by writing:

const jump = (h) => {
  const url = location.href;
  location.href = "#" + h;
  history.replaceState(null, null, url);
}
`
const button = document.querySelector('button')
button.addEventListener('click', () => {
  jump('b')
})

We have the jump function with the h parameter which is the ID of the element we want to scroll to.

Next, we get the current URL with location.href .

Then we add the hash with the ID h to it to jump to the element with ID h .

And then we call history.replaceState with url as the 3rd argument to replace the hash URL with the original.

Next, we get the button with document.querySelector .

And then we call addEventListener with 'click' to add a click listener.

The 2nd argument is the click listener which calls jump with 'b' to scroll to the div with ID b .

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 *