{"id":322209,"date":"2020-10-05T07:43:12","date_gmt":"2020-10-05T14:43:12","guid":{"rendered":"https:\/\/css-tricks.com\/?p=322209"},"modified":"2020-10-05T07:43:13","modified_gmt":"2020-10-05T14:43:13","slug":"how-to-make-an-unobtrusive-scroll-to-top-button","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/how-to-make-an-unobtrusive-scroll-to-top-button\/","title":{"rendered":"How to Make an Unobtrusive Scroll-to-Top Button"},"content":{"rendered":"\n

A button to return to the top of the page allows the user to quickly return to the top of the page without making too much effort. This can be very useful when the page has a lot of content or which happens, for example, on one page websites, when infinite scrolling is used, or on mobile devices where different screen sizes can cause the content to scroll extend.<\/p>\n\n\n\n

Those buttons usually float in the bottom corner of sites and then take you back to the top of the page when clicked. They are pretty easy to create with JavaScript. But visually, we are looking for it to be non-obtrusive while still being a large enough target to tap or click. Let\u2019s look at a few ways we can do this, starting simple, then improving things as we go.<\/p>\n\n\n

Option 1: Keep it simple<\/h3>\n\n\n

First, we select the button in JavaScript.<\/p>\n\n\n\n

var scrollToTopBtn = document.getElementById(\"scrollToTopBtn\")<\/code><\/pre>\n\n\n\n

Now document.documentElement<\/code> returns the root element of the document. We need it to get the offset values. So, next let\u2019s save it in a variable called rootElement<\/code> \u2014 that way it\u2019s easier to call in the code.<\/p>\n\n\n\n

var rootElement = document.documentElement<\/code><\/pre>\n\n\n\n

We’ll add a click event listener to the button:<\/p>\n\n\n\n

function scrollToTop {\n\u00a0 \/\/ scroll to top logic\n}\n\nscrollToTopBtn.addEventListener(\"click\", scrollToTop)<\/code><\/pre>\n\n\n\n

Then, inside the scrollToTop<\/code> function, we will make it scroll to the top of the screen with the scrollTo<\/code> method.<\/p>\n\n\n\n

function scrollToTop() {\n\u00a0 \/\/ Scroll to top logic\n\u00a0 rootElement.scrollTo({\n\u00a0 \u00a0 top: 0,\n\u00a0 \u00a0 behavior: \"smooth\"\n\u00a0 })\n}<\/code><\/pre>\n\n\n\n

We can style the button up a bit as well:<\/p>\n\n\n\n

#scrollToTopBtn {\n\u00a0 background-color: black;\n\u00a0 border: none;\n\u00a0 border-radius: 50%;\n\u00a0 color: white;\n\u00a0 cursor: pointer;\n\u00a0 font-size: 16px;\n\u00a0 line-height: 48px;\n\u00a0 width: 48px;\n}<\/code><\/pre>\n\n\n\n

Now we\u2019re able to drop the button somewhere down the page, say, the footer:<\/p>\n\n\n\n

<footer>\n\u00a0 <!-- Scroll to top button -->\n\u00a0 <button id=\"scrollToTopBtn\">☝️<\/button>\n<\/footer><\/code><\/pre>\n\n\n\n

And we get this:<\/p>\n\n\n\n