How to Create a Scroll Image Animation with jQuery?

Estimated read time 3 min read

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

HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Scroll Image Animation with jQuery</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		#container {
			height:4000px;
		}
		
		#image {
			position:fixed;
			top:50%;
			left:50%;
			transform:translate(-50%, -50%);
			width:200px;
			height:200px;
			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>
	</div>
	
	<img id="image" src="image.jpg">
	
	<script>
		$(document).ready(function(){
			$(window).scroll(function(){
				if($(this).scrollTop() > 500){
					$("#image").fadeIn();
				}
				else{
					$("#image").fadeOut();
				}
				
				var scrollPos = $(this).scrollTop();
				$("#image").css({
					"transform": "translate(-50%, " + scrollPos/4 + "px)"
				});
			});
		});
	</script>
</body>
</html>

In this example, we have a div with the ID “container” that has a height of 4000 pixels, allowing it to have a scrollbar. We also have an img element with the ID “image” that will be animated as the user scrolls down the page.

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 500 pixels, we call the fadeIn() method on the “image” element, which will display it. When the user scrolls back up to less than 500 pixels, we call the fadeOut() method on the “image” element, which will hide it again.

In addition, we calculate the current scroll position of the window and set the “transform” property of the “image” element to translate(-50%, {scrollPos/4}px). This will move the “image” element up and down by one-quarter of the scroll position, giving it a parallax effect.

Note that in this example, we are using an image called “image.jpg”, but you can replace this with the path of your own image. Also, you can adjust the scroll position at which the image appears and the speed of the animation by modifying

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply