Imagine you are building a website and want to enhance user experience with a smooth scroll-to-top animation without relying on jQuery duplicates. You're in luck! In this article, we will guide you through the process of implementing a scroll-to-top functionality using vanilla JavaScript.
Firstly, let's create a basic HTML structure. Within your HTML file, add a button for users to click on to scroll to the top of the page smoothly. Here is an example code snippet to get you started:
<title>Scroll to Top</title>
<div id="content">
<!-- Your website content here -->
</div>
<button id="scrollToTopBtn">Scroll To Top</button>
Now, let's move on to the JavaScript part. Create a new JavaScript file (such as `script.js`) and add the following code to handle the scroll-to-top functionality without using jQuery:
const scrollToTopBtn = document.getElementById('scrollToTopBtn');
const rootElement = document.documentElement;
function scrollToTop() {
rootElement.scrollTo({
top: 0,
behavior: 'smooth'
});
}
scrollToTopBtn.addEventListener('click', scrollToTop);
window.addEventListener('scroll', () => {
if (rootElement.scrollTop > 100) {
scrollToTopBtn.style.display = 'block';
} else {
scrollToTopBtn.style.display = 'none';
}
});
In this JavaScript code, we first grab the button element and the root element of the document. The `scrollToTop` function smoothly scrolls the page to the top when the button is clicked. We then add an event listener to the button to trigger the scroll functionality.
Additionally, we listen for the scroll event on the window to show or hide the scroll-to-top button based on the user's scrolling position. If the user has scrolled more than 100 pixels, the button is displayed; otherwise, it is hidden.
By following these steps, you can easily add a scroll-to-top animation using plain JavaScript, avoiding the need for duplicate jQuery code. Your website visitors will appreciate the seamless scrolling experience you provide. Happy coding!