How to Create a Scroll to Top Animation with jQuery?

Estimated read time 3 min read

Here’s an example of how to create a Scroll to Top Animation with jQuery:

HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Scroll to Top Animation with jQuery</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		#container {
			height:2000px;
		}
		
		#top-btn {
			position:fixed;
			bottom:20px;
			right:20px;
			display:none;
		}
	</style>
</head>
<body>
	<div id="container">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.</p>
		<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.</p>
		<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.</p>
		<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet.</p>
		<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.</p>
	</div>
	
	<button id="top-btn">Top</button>
	
	<script>
		$(document).ready(function(){
			$(window).scroll(function(){
				if($(this).scrollTop() > 100){
					$("#top-btn").fadeIn();
				}
				else{
					$("#top-btn").fadeOut();
				}
			});
			
			$("#top-btn").click(function(){
				$("html, body").animate({scrollTop: 0}, 1000);
				return false;
			});
		});
	</script>
</body>
</html>

In this example, we have a div with the ID “container” that has a height of 2000 pixels, allowing it to have a scrollbar. We also have a button with the ID “top-btn” that will allow us to scroll to the top of the page with a smooth animation.

We also have a script tag where we add our jQuery code. In the script, we listen for a scroll event on the window. When the user scrolls down more than 100 pixels, we call the fadeIn() method on the “top-btn” button, which will display it. When the user scrolls back up to less than 100 pixels, we call the fadeOut() method on the “top-btn” button, which will hide it again.

In addition, we add a click event listener on the “top-btn” button. When the button is clicked, we call the animate() method on both the html and body elements, which will smoothly scroll to the top of the page with

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply