Home »
jQuery
jQuery - Chaining
jQuery Chaining: Learn about the Chaining in jQuery, how it works, and its example.
Submitted by Pratishtha Saxena, on September 25, 2022
Chaining
Chaining means connecting one thing to another one by one. When we talk about the method chaining in jQuery it means – that the multiple animation methods are written one after another. Generally, we define the method one by one. But this way can be complicated when there are a lot of methods to be declared for a single element. Hence with the help of method chaining, we can define all the methods in a single line. This makes it easy to understand and the code cleaner.
jQuery Chaining Syntax (1)
$("selector").effect1().effect2().effect3()...;
This way of defining effects and animations will execute them one by one. First, effect1 will be executed then effect2 and finally effect3. Sometimes, when a lot of methods are declared for an element, then this single line can become a very long line. To avoid this, we can also declare the methods in different lines using the same selector.
jQuery Chaining Syntax (2)
$("selector").effect1()
.effect2()
.effect3()
...and so on;
This will help to make the code look clearer and more understandable. This way we can figure out all the methods applied to the selector.
Let's see the following example, where all the animating methods are declared using chaining.
jQuery Chaining Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h1>jQuery - Chaining Example</h1>
<p>Click the button.</p>
<button>Start Animations</button>
<hr>
<img id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
<hr>
<h3></h3>
</body>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function () {
$('img').animate({
height: 200,
width: 300
}, 4000)
.animate({
opacity: 0.5
}, 4000)
.css("border", '5px solid #000');
})
});
</script>
</html>
Output: