Certainly! You can use JavaScript to create a smooth scroll-to-top animation. Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll to Top Animation</title>
<style>
body {
height: 1500px; /* Adding some height to enable scrolling */
}
#scrollToTopBtn {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Content goes here -->
<button id="scrollToTopBtn" onclick="scrollToTop()">Scroll to Top</button>
<script>
// Show/hide scroll-to-top button based on scroll position
window.onscroll = function() {
showScrollToTopButton();
};
function showScrollToTopButton() {
var scrollToTopBtn = document.getElementById("scrollToTopBtn");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
scrollToTopBtn.style.display = "block";
} else {
scrollToTopBtn.style.display = "none";
}
}
// Smooth scroll to top function
function scrollToTop() {
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, currentScroll - currentScroll / 8);
}
}
</script>
</body>
</html>
In this example:
The button with the id scrollToTopBtn is initially hidden (display: none).
The showScrollToTopButton function is used to show or hide the button based on the scroll position.
The scrollToTop function is responsible for the smooth scroll animation. It uses the
window.requestAnimationFrame method for a smoother animation effect.
Adjust the button styles and animation parameters as needed for your specific design preferences.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Certainly! You can use JavaScript to create a smooth scroll-to-top animation. Here's an example:
In this example:
Adjust the button styles and animation parameters as needed for your specific design preferences.