Delay animations in jQuery


In this lesson, you will learn how to delay effects or animations using .delay() function in jQuery. This function is used in a scenario where you want to delay a specific animation. It allows you to delay the execution of the following functions in a sequence or queue.

Introduction to delay animations in jQuery

The syntax of the delay function is:

.delay (duration [, queue name])

The only parameter you need here is the duration – time in milliseconds to delay the execution of methods that follow the .delay() function in the sequence. It can be given as ‘string’ or ‘number’. The string representation for 200, 400, and 600 milliseconds are fast, normal, and slow, respectively.

Let’s say you want to add a delay of 4 seconds between two animations on a selected web element.

$( "#selected_element").slideUp(300).delay(400).fadeIn(400);

It is equivalent if written as:

$("#selected_element").slideUp(300).delay('normal').fadeIn(400);

Example of Delay Animations in jQuery

In this example, we will have 3 DIVs of equal width and height, but with different background-color. All these DIVs are animated but with different delay is applied.

The HTML

<div id="container">
   <p><a href="#" id="anim">Start animation</a></p>
   <div class="box one"></div>
   <div class="box two"></div>
   <div class="box three"></div>
</div>

The Style

<style>* {
	box-sizing: border-box;
}

body {
	font-family: 'Open Sans', sans-serif;
	color: #333;
	font-size: 14px;
}

a:hover,
a {
	text-decoration: none;
}

.box {
	width: 100px;
	height: 100px;
	margin: 2px;
}

.one {
	background-color: #d9eb4b;
}

.two {
	background-color: #00A9FE;
}

.three {
	background-color: #fd6bb6;
}

#container {
	margin: 20px;
	padding: 10px;
	border: 1px solid #ccc;
	width: 400px;
}

</style>

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" >
	</script> <script >
	$(document).ready(function () {
		$('#anim').click(function () {
			$('.one').animate({
				width: '120px'
			}, {
				start: function () {
					$('#anim').text("Animation in process");
				}
			});
			$('.two').delay(1000).animate({
				width: '140px'
			});
			$('.three').delay(2000).animate({
				width: '160px'
			}, {
				complete: function () {
					$('#anim').text("Animation complete");
				}
			});
		});
	}); 
</script>

Animation Started
Animation in Progress
Animation Completed

 

jQuery Animating Elements Tutorial Home jQuery Events
Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply