Bouncing Ball Animation using jQuery

This article is to create a bouncing ball animation effect using jQuery. Just a quick fun post. This animation effect is created based on different parameters like the bouncing count, speed and etc. In a previous tutorial, we have seen more examples of working with jQuery animation. For example, jQuery background animation on page scroll, jQuery parallax slider and more.

In this example, it shows a table tennis ball on the bottom of a DIV element. On clicking the ball, the jQuery function will be called to create bouncing animation with the ball. The bouncing count and the speed will be passed to this function. Based on these parameters the bouncing height and the speed ratio will be calculated to animate the ball using jQuery animate().

View Demo

bouncing-ball

HTML Code and Styles of the Bouncing Ball

The following code shows the HTML and the styles used to display the bouncing ball image. By referring this image element, the jQuery bouncing animation function will be triggered on clicking the ball.

<style>
#bouncing-ball {
	height: 100px;
	position: absolute;
	bottom: 0px;
	left: 50%;
	margin-left: -50px;
}

#outterDiv {
	height: 340px;
	background: #36a094;
	position: relative;
}

.banner-info {
	padding: 15px;
	color: #FFF;
}
</style>
<h1>Demo Bouncing Ball Animation using jQuery</h1>
<div id="outterDiv">
    <div class="banner-info">Click the ball to see the
        bouncing animation</div>
    <img id="bouncing-ball" src="bouncing-ball.png"></img>
</div>

jQuery Bouncing Animation Function

The following code shows the jquery function to create the bouncing animation effect on the ball image element. It receives the number of times the bouncing should happen and the bouncing speed as its parameters. using these parameters, the bouncing height is calculated for each bounce and set as the animation property using jQuery animate() function. 

<script src="jquery-3.2.1.min.js"></script>
<script>
	function bounce(bouncingCount, speed) {
		var top = 200;
		var speedRatio = speed / top;
		var heightRatio = top / bouncingCount;

		for (var i = 1; i <= bouncingCount; i++) {
			$('#bouncing-ball').animate({
				'bottom' : top
			}, speed);
			$('#bouncing-ball').animate({
				'bottom' : 0
			}, speed / 2);
			top = top - (heightRatio);
			speed = speedRatio * top;
		}
	}

	$("#bouncing-ball").click(function() {
		bounce(10, 500);
	});
</script>

Bouncing Ball Animation Example – Screenshot

The following image shows the screenshot of the bouns=cing ball animation example.

bouncing-ball-animation-screenshot

View DemoDownload

This jQuery code tutorial was published on October 23, 2017.

↑ Back to Top