Learn how to build and design websites with our tutorials.

jQuery Callback Functions Tutorial

View Tutorial Contents


What Is A Callback Function?

A callback function is a function that is passed to another function as a parameter.

Within jQuery, a callback function is executed after all of the effects within a jQuery method are finished.


jQuery Callback Functions Syntax

The syntax for a callback function would typically be something like:


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

Or


$(selector).method({CSS parameters}, speed, callback);

The example below shows you how to pass a function to jQuery method as a parameter.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>

<h1>
Heading
</h1>

<p>
This is a paragraph.
</p>

<button id="fade-out">Fade Out</button> <button id="fade-in">Fade In</button>

<script>

$(document).ready(function(){
	$("#fade-out").click(function(){
		$("div").fadeOut("slow", function(){
			alert("The <div> is gone!");
		});
	});
	$("#fade-in").click(function(){
		$("div").fadeIn("slow", function(){
			alert("The <div> is back!");
		});
	});
});

</script>
</body>
</html> 

The example below contains two callback functions.

This is a paragraph.