×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery - Callback Function

jQuery Callback Function: Learn about the Callback Function in jQuery, how it works, and its example.
Submitted by Pratishtha Saxena, on September 25, 2022

Callback Function

By callback function, we mean that it is a function declared which will get executed only when the jQuery effect has been completed. Once the running effect gets finished, only then the callback function is triggered. This is an important and useful function of jQuery, which helps us to know to that the effects have been completed and now the custom function declared is getting executed. Therefore, we can define this callback function in such a way that we need to do it once the animation has been finished.

jQuery Callback Function Dyntax

$(selector).effectName(speed, callback);

In any jQuery method, speed and callback are the two basic and optional parameters that it accepts. Hence, the callback function can be defined over here. The following syntax shows how to specifically define a function.

jQuery syntax to define a function

$(selector).effectName(speed, function(){
	<!-- function body -->
});

This way the custom function can be declared and executed once the effect animation has been completed.

Below is the example showing the implementation of the callback function. When the hide() method completes its task, then by using its callback function it shows the appropriate text. Similarly, when the show() method finishes its task, it shows the text accordingly.

jQuery Callback Function 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>
    <h2>jQuery Effects - Callback Function</h2>
    <p>Click the button to implement the Callback Function on the image.</p>
    <button id="btn1">Hide</button>
    <button id="btn2">Show</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() {
        $('#btn1').click(function() {
            $('img').hide('slow', function() {
                $('h3').html('The Image is now Hidden.');
                $('img').css("display", "none");
            })
        });
    
        $('#btn2').click(function() {
            $('img').show('slow', function() {
                $('h3').html('The Image is now Visible.');
            })
        })
    });
  </script>
</html>

Output:

jQuery - Callback Function


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.