2 Example(s) of JQuery Toggle


Description :

In this example, we are going to hide and show the text with same button using toggle() function.


JQuery Toggle Example - 1
<!DOCTYPE html>
<html>

<head>
    <title>Welcome to LearnKode - A code learning platform</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $(".toggle").click(function() {
                $("p").toggle();
            });
        });
    </script>
</head>

<body>

    <p>Click to toggle between hide and show of this text</p>

    <button class="toggle">Toggle</button>

</body>

</html>

Output

Description :

In this example we are going to show three arguments are passed to the toggle() method. The numeric value 1000 is the duration of display effect. “Linear” is the easing function used. There is a callback method also passed to the toggle method. This method is called after the toggle between hide and display of the <div> element.


JQuery Toggle Example - 2
<!DOCTYPE html>
<html>
<head>

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

<style>
img{
width: 500px;
height: 200px;
}
button{
    height: 40px;
    width: 250px;
    border: 1px solid black;
    border-radius: 10px;
    background-color: aqua;
}
</style>

<script>
$(document).ready(function(){
  $(".togglebtn").click(function(){
    $("img").toggle(1000,"swing",function(){
      alert("toggle method is finish!");
    });
  });
});
</script>
</head>
<body>
<h1 style="color:lightgreen">Click to the button and then see</h1>
<button class="togglebtn">Toggle</button><br>
<img src="https://appwrk.com/wp-content/themes/appwrk_theme/images/logo-dark.png">
</body>
</html>

Output