Legacy Content Notice: This post from 2016 demonstrates older JavaScript patterns for smooth scrolling. Modern browsers now support CSS
scroll-behavior
and thescrollTo
API with built-in smooth scrolling. For comprehensive modern JavaScript development practices, see our Modern JavaScript Development Guide.
A popular trend you see on many websites is the back to top button, where the user will click this button to automatically scroll back to the top of the page. In a previous tutorial I exampled how you can do this using jQuery using the animate function to smooth scroll the browser back to the top. Back To Top With jQuery I used this script a lot over the years on multiple new websites I worked on, but recently I've been putting a lot more effort into the performance of websites and working on how you can speed up the page loading times.
One of the biggest things I've been working on is removing the need to load jQuery into my application and simply using pure JavaScript.
I know there's a place for jQuery and I won't say you don't need to use it at all but if all you're doing is simple click events then normally there isn't a need to use jQuery. Therefore I decided to look again at this jQuery smooth scroll to top function and achieve the same thing by using pure Javascript and removing the dependency on jQuery.
Modern Implementation (2024)
Method 1: CSS Scroll Behavior (Recommended)
The simplest modern approach uses CSS scroll-behavior
for automatic smooth scrolling:
html {
scroll-behavior: smooth;
}
.back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
background: #007bff;
color: white;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
cursor: pointer;
opacity: 0;
transition: opacity 0.3s ease;
}
.back-to-top.visible {
opacity: 1;
}
<button class="back-to-top" id="backToTop" aria-label="Back to top">↑</button>
const backToTopButton = document.getElementById("backToTop");
// Show/hide button based on scroll position
window.addEventListener("scroll", () => {
if (window.pageYOffset > 300) {
backToTopButton.classList.add("visible");
} else {
backToTopButton.classList.remove("visible");
}
});
// Scroll to top when clicked
backToTopButton.addEventListener("click", () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
});
Method 2: JavaScript Smooth Scrolling
For more control or older browser support:
class BackToTopManager {
constructor() {
this.button = this.createButton();
this.bindEvents();
}
createButton() {
const button = document.createElement("button");
button.className = "back-to-top";
button.innerHTML = "↑";
button.setAttribute("aria-label", "Back to top");
document.body.appendChild(button);
return button;
}
bindEvents() {
// Use Intersection Observer for better performance
const observer = new IntersectionObserver(
([entry]) => {
this.button.classList.toggle("visible", !entry.isIntersecting);
},
{ threshold: 0.1 }
);
// Observe a sentinel element at the top
const sentinel = document.createElement("div");
sentinel.style.height = "1px";
document.body.insertBefore(sentinel, document.body.firstChild);
observer.observe(sentinel);
// Scroll to top on click
this.button.addEventListener("click", this.scrollToTop.bind(this));
}
scrollToTop() {
// Modern smooth scroll
if ("scrollBehavior" in document.documentElement.style) {
window.scrollTo({
top: 0,
behavior: "smooth",
});
} else {
// Fallback for older browsers
this.smoothScrollToTop();
}
}
// Fallback smooth scroll for older browsers
smoothScrollToTop() {
const scrollStep = -window.scrollY / (300 / 15);
const scrollInterval = setInterval(() => {
if (window.scrollY !== 0) {
window.scrollBy(0, scrollStep);
} else {
clearInterval(scrollInterval);
}
}, 15);
}
}
// Initialize
const backToTop = new BackToTopManager();
Method 3: Advanced with Progress Indicator
class AdvancedBackToTop {
constructor() {
this.button = this.createButton();
this.bindEvents();
}
createButton() {
const container = document.createElement("div");
container.className = "back-to-top-container";
container.innerHTML = `
<button class="back-to-top" aria-label="Back to top">
<svg class="progress-ring" width="50" height="50">
<circle class="progress-ring-circle"
cx="25" cy="25" r="20"
fill="transparent"
stroke="#007bff"
stroke-width="3"/>
</svg>
<span class="arrow">↑</span>
</button>
`;
document.body.appendChild(container);
return container.querySelector(".back-to-top");
}
bindEvents() {
window.addEventListener("scroll", this.updateProgress.bind(this));
this.button.addEventListener("click", this.scrollToTop.bind(this));
}
updateProgress() {
const scrolled = window.pageYOffset;
const maxHeight = document.body.scrollHeight - window.innerHeight;
const scrollProgress = scrolled / maxHeight;
// Update progress ring
const circle = this.button.querySelector(".progress-ring-circle");
const circumference = 2 * Math.PI * 20;
const offset = circumference - scrollProgress * circumference;
circle.style.strokeDasharray = circumference;
circle.style.strokeDashoffset = offset;
// Show/hide button
this.button.classList.toggle("visible", scrolled > 300);
}
scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
}
// Initialize
const advancedBackToTop = new AdvancedBackToTop();
Legacy Implementation (2016 - Historical Reference)
The HTML
First you need to have a HTML element on the page for the user to click. This can be a button, a div or a span, anything that you can add a click event onto.
<div class="back-to-top pointer" onclick="scrollToTop();return false;">
Back to top ^
</div>
Notice the onclick attribute in the above HTML, this will now run the scrollToTop() function. For this function we want to scroll the user back to the top, but to make it look like smooth scrolling we will need to scroll the page slowly in increments. First we check to see if the page is already at the top of the window, if not then we continue with the script.
if (document.body.scrollTop != 0 || document.documentElement.scrollTop != 0) {
}
We then take the window and scroll -50px to the top of the window.
window.scrollBy(0, -50);
After scrolling up 50px we need set a timeout to repeat this scrollToTop() function ever 10 milliseconds. This will create the smooth scroll effect back to the top of the page until it lands back to vertical position 0.
<script>
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
</script>
Related Modern Guides
- Modern JavaScript Development Guide - Comprehensive modern JavaScript practices
- JavaScript Helper Functions - Useful utility functions for modern development
Key Modern Advantages
- Better Performance: Intersection Observer vs scroll events
- Native Smooth Scrolling: Built-in browser support
- Accessibility: Proper ARIA labels and semantic HTML
- Progressive Enhancement: Fallbacks for older browsers
- Reduced JavaScript: CSS handles smooth scrolling