Chaining
Most jQuery methods return the same jQuery object, so you can call another method right after:
$('#msg')
.text('Saved!')
.css('color', 'green')
.slideDown()
.delay(1500)
.slideUp();
The element is selected only once, which is shorter and faster.
Put each method on a new line for readability.
Callbacks
Effects run asynchronously — the next line of code does not wait. Code that must run after an effect goes in a callback:
$('#popup').fadeOut(400, function () {
$(this).remove(); // runs only when fading is done
});
Getters break the chain
Methods that return a value (.text(), .val(), .attr('href') without a new value) cannot be chained further.
Example
Example — Chaining and callback
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<button id="go">Send message</button>
<p id="status" style="display:none;padding:8px"></p>
<div id="card" style="margin-top:10px;padding:14px;background:#fff3cd;width:220px">Click the card to remove it</div>
<script>
$(function () {
$('#go').click(function () {
$('#status')
.stop(true, true)
.text('Message sent ✓')
.css({ background: '#d3f9d8', color: '#2b8a3e' })
.slideDown(300)
.delay(1500)
.slideUp(300);
});
$('#card').click(function () {
$(this).fadeOut(500, function () {
$(this).remove();
alert('Card removed after the fade finished.');
});
});
});
</script>