Advertisement

Google Ad Slot: content-top

jQuery Chaining


With jQuery chaining, you can perform multiple actions on the same element in a clean, readable way.

Chaining means combining multiple jQuery methods on the same selector in one line, instead of repeating the selector over and over.


jQuery Method Chaining


Method chaining allows you to call multiple jQuery methods on the same element in a single statement.

To chain an action, you simply append the action to the previous action.


It helps:

  • Keep code compact & readable
  • Ensure methods run one after another
  • Reduce repetition of selectors



The following example chains together the css()slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down:

Example
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#box")
.css({
"background-color": "#2ecc71",
"color": "white",
"border-radius": "10px"
})
.slideUp(1000)
.slideDown(1000)
});
});
</script>
Try it yourself