jQuery toggle()

Toggling between the hide() and show() methods can be done easily using the jQuery toggle() method. This type of animation is often used in jQuery projects.

toggle() method is used to toggle the selected elements.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").toggle();
});
});
</script>
</head>
<body>
<div style="background: red; height: 50px; width: 50px; border-radius: 120px;"></div> <br>
<button>Toggle</button>
</body>
</html>

Speed, callback, and display are some parameters that can be used for enhancing the animation (toggling). All these parameters are optional.

Syntax:

$(selector).toggle(speed, callback);
$(selector).toggle(display);

Speed:

  • Speed is an optional parameter that specifies the speed of the delay in the animation, with a default value of 400 milliseconds.

Callback:

  • Callback is the optional function to be executed once the toggle() method’s execution is complete.

Display:

  • The display parameter can take two values: either true or false.
  • If the value of the display parameter is true, it displays the element. Otherwise, it hides the element.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").toggle(3000);
});
});
</script>
</head>
<body>
<div style="background: blue; height: 50px; width: 50px; border-radius: 120px;"></div> <br>
<button>Toggle</button>
</body>
</html>