In jQuery, a callback function is a function that is passed as an argument to another function and is executed after the first function has finished executing. Callback functions are commonly used in asynchronous operations such as event handling, animations, and AJAX requests.
Here’s an example of how to use a callback function in jQuery:
$('button').click(function() {
$('p').fadeOut('slow', function() {
alert('Animation complete.');
});
});
In this example, when a user clicks a button element, a paragraph element will be faded out slowly using the fadeOut()
method. The second argument of fadeOut()
is a callback function that will be executed once the animation is complete. In this case, the callback function displays an alert message to the user.
Callback functions can also be defined separately and then passed as arguments to jQuery methods. For example:
function myCallback() {
console.log('Callback function executed.');
}
$('button').click(myCallback);
In this example, a callback function named myCallback()
is defined and then passed as an argument to the click()
method of a button element. When the button is clicked, the myCallback()
function will be executed.