toggle() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:toggle

Description

The toggle() method toggles between hide() and show() for the selected elements.

Syntax

$(selector).toggle(speed,easing,callback);
Parameter Require DescriptionValue
speed Optional.speed of the hide/show effectPossible values: milliseconds "slow" "fast"
easingOptional.speed of the element in different points of the animation. Default value is "swing"
callback Optional. A function to be executed after the toggle() method is completeda function

Possible easing values:

  • "swing" - slower at the beginning/end, but faster in the middle
  • "linear" - in a constant speed

The following code shows how to Toggle between hide and show for all <p> elements:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });//  w  w w .  j a  v a2s.  c om
});
</script>
</head>
<body>

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

<button>Toggle between hide() and show()</button>

</body>
</html>

The following code shows how to Toggle between colors when clicking on a <p> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
</script>/*from w w  w .  jav a 2s .c  om*/
<script>
$(document).ready(function(){
    $("p").toggle(
        function(){$("p").css({"color": "red"});},
        function(){$("p").css({"color": "blue"});},
        function(){$("p").css({"color": "yellow"});},
        function(){$("p").css({"color": "green"});
    });
});
</script>
</head>
<body>

<p style="font-size:40px">Click me.</p>

</body>
</html>

Related Tutorials