We can automatically scroll to a specific HTML element on the page simply by linking to its ID.

For example, let’s say we want to automatically scroll to a form on the page.

We can simply add an ID to it, like so: <form id="signup">.

Then, use an anchor link (#) to send the user directly to this section:

<a href="#signup">Register now</a>

This method uses native (built-in) HTML capabilities, so it has many advantages:

  • We can create a link that sends the user directly to a particular section. For instance, when clicking on a link that includes #signup (like https://example.com/join/#signup), the user will go directly to the registration form on that page.
  • It doesn’t require additional / custom functions.
  • Native solutions are always easier to use because they already take care of accessibility aspects (like keyboard focus) and are well supported in most browsers.

Method 2: JavaScript

It is not always possible to use the native method of anchor links.

Sometimes we need to use JavaScript to trigger the scrolling (e.g. if the scrolling is required as part of another JavaScript function).

Fortunately, it’s very easy to auto-scroll to an element using JavaScript as well.

First, let’s store the form element in a new variable:

const form = document.querySelector('#signup');

Then, we’ll use one of these JavaScript methods to perform the auto-scroll.

This option is related to the first method we discussed - the anchor links.

We can simply simulate clicking an anchor link using JavaScript, like this:

location.href = '#signup';

This way the native anchor link behavior is triggered and the URL will also change (so that #signup is added).

Option 2: scrollIntoView

This simple line of code will scroll to the top of form:

form.scrollIntoView();

By default, scrollIntoView scrolls to the top of the element.

If you want to scroll to the bottom of the element (rather than the top), you can pass false as the parameter:

form.scrollIntoView(false);

We can also modify these settings using scrollIntoViewOptions - an object to adjust the properties of scrollIntoView.

For example, we can set it to scroll to the center of the element or force smooth scrolling:

form.scrollIntoView({
	behavior: 'smooth',
	block: 'center',
});

Option 3: scrollTo

Another JavaScript option is the scrollTo method.

Unlike scrollIntoView which binds to a specific element, this method scrolls to certain coordinates on the page. So, if a simple scroll to the top of an element is all that’s required, I’d stick with option 1 or option 2.

We can set these coordinates so that it eventually scrolls to the top of the form:

window.scrollTo(0, form.getBoundingClientRect().top + window.scrollY);

Using the options parameter, we can configure additional settings, such as forcing the smooth scrolling effect via JavaScript:

window.scrollTo({
	top: form.getBoundingClientRect().top + window.scrollY,
	behavior: 'smooth',
});

References