← Back toHTML DOM

Prevent the page from scrolling to an element when it is focused

Written byPhuoc Nguyen
Created
19 Oct, 2021
Category
Level 1 — Basic
An element can be focused by either using the `autofocus="true"` attribute or calling the `element.focus()` method. In both cases, the browser will automatically scroll the element into the viewport. It is not a problem in most cases but I have seen a few scenarios where we would like to avoid the behaviour.
For example, focusing on a text field inside a modal automatically might scroll the page to the top.
There are two solutions to prevent this behaviour.

Use the preventScroll option

We can pass the `preventScroll` option to the `focus()` method as following:
js
element.focus({
preventScroll: true,
});
However, the option is not fully supported in all browsers. Check out the web-platform-tests and Can I use pages.

Scroll to the previous point

This approach works in all browsers. We store the mouse location before calling the `focus()` method, and then scroll to that location later:
js
const x = window.scrollX;
const y = window.scrollY;
elem.focus();

// Scroll to the previous location
window.scrollTo(x, y);
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn