Callback function in jQuery


The jQuery callback function is executed after the current effect is complete, to learn the details of the jQuery callback function, read along to the following lesson of Taimienphi.vn.


In the following lesson, Taimienphi.vn will introduce you to the callback function in jQuery. In addition, readers can refer to some other jQuery lessons on Taimienphi.vn to learn more about Chaining in jQuery.

Learn the callback function in jQuery

Callback function in jQuery

JavaScript instructions are executed one line at a time. However, because the jQuery effect takes time to complete, the next line of code can be executed while the previous effect is still running.

To prevent this from happening, jQuery provides a function called callback for each effect mode.

The callback function in jQuery is executed after the current effect is completed. The function is passed as a parameter to the effect method and appears as the final argument of the method.

For example, the basic syntax of effect modes slideToggle () In jQuery, the callback function looks like this:

$ (selector) .slideToggle (duration, callback);

Example 1: In the example below, the slideToggle () and alert () commands are placed next to each other. When we click the activate button without waiting for the transition effect to complete, the screen will display a warning:

Ham callback in jquery

The output will look like the following:

Ham callback in jquery 2

Example 2: In the example below we will place the alert () in the callback function for the slideToggle () method. When we click the activate button, a warning will be displayed after the slide transition is completed:

Ham callback in jquery 3

The output will look like the following:

ham callback in jquery 4

Similarly we can assign callback functions to other jQuery effect methods like show (), hide (), fadeIn (), fadeOut (), animate (), ….

Note: If the effect method is applied to multiple elements, the callback function is executed for each selected element in turn rather than executing for all the elements at once.

For example: The following example illustrates how the callback function is executed in turn for each selected element:

ham callback in jquery 5

The output will look like the following:

ham callback in jquery 6

In the example above, the output will display the same message twice for the elements h1 and p when we click the enable button.

So the above lesson you have read with Taimienphi.vn learn about the callback function in jQuery. In addition, if you have any questions or questions, you can leave your comments in the comment section below the article.

https://thuthuat.taimienphi.vn/ham-callback-trong-jquery-51491n.aspx
In the next lesson, Taimienphi.vn will introduce you more about the Getter and Setter methods in jQuery.

.

Add a Comment

Your email address will not be published. Required fields are marked *