jQuery Callback Functions

A callback function is executed after the current effect is 100% finished.

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.

Examples

The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

$(document).ready(function(){
    $("button").click(function(){
        $("p").hide("slow", function(){
            alert("The text is now hidden");
        });
    });
});

View Demo

jQuery Method Chaining

In this lesson you will learn how chain multiple methods in jQuery.

jQuery Method Chaining

The jQuery provides another robust feature called method chaining that allows us to perform multiple action on the same set of elements, all within a single line of code.

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

$(document).ready(function(){
    $("button").click(function(){
        $(".Chaining").css("color", "#FBBC09").slideUp(2000).slideDown(2000);
    });
});

View Demo

jQuery Stop Animations

In this tutorial you will learn how to stop running animations using jQuery.

jQuery stop() Method

The jQuery stop() method is used to stop animations or effects before it is finished.

Here’s a simple example that is showing the jQuery stop() method in real action in which you can start and stop the animation on click of the button.

$(document).ready(function(){
    // Start animation
    $(".start-btn").click(function(){
      $(".img").animate({left: "+=150px"}, 2000);
    });

    // Stop running animation
    $(".stop-btn").click(function(){
      $(".img").stop();
    });
    
    // Start animation in the opposite direction
    $(".back-btn").click(function(){
      $(".img").animate({left: "-=150px"}, 2000);
    });

    // Reset to default
    $(".reset-btn").click(function(){
      $(".img").animate({left: "0"}, "fast");
    });
});

View Demo

jQuery Animation – Effects

The jQuery animate() method is used to create custom animations. The animate() method is typically used to animate numeric CSS properties, for example, width, height, margin, padding, opacity, top, left, etc.

The following example is showing a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 400px:

$("button").click(function(){
    $(".animate").animate({left: '400px'});
}); 

View Demo

jQuery Sliding – Effects

The jQuery slide methods slide elements up and down.

jQuery Sliding Methods

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

  • slideDown()
  • slideUp()
  • slideToggle()
$("#slide").click(function(){
    $("#panelslide").slideDown();
});

View Demo