jQuery Effects - Toggle

jQuery Effects - Toggle: Learn about the jQuery toggle() method, how it works, and its example.
Submitted by Pratishtha Saxena, on September 22, 2022

jQuery toggle() Method

By the word toggle, we mean to switch between any two cases. Generally, we are used to the toggle property of an MS word application, where when we use to toggle the capital letters become small and all the small letters switch to capital. Therefore, toggle means switching between events.

In jQuery, when we talk about the toggle() method, we mean to toggle between the hide() and the show() methods. This means, that if an element is initially in the hidden state, then this method will make it display and if it is already at display then this will hide the element.

toggle() Method Syntax

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

Similar to the hide() and show() methods of jQuery, the toggle() method also takes in optional parameters such as – speed & callback. The speed indicates the speed to display or hide the content in milliseconds. Whereas the callback is a function that gets initiated when the toggle() method completes its task.

Let's have a better understanding of this method with the help of the following given example. When the given button is clicked, then it toggles the element between hiding and showing events. Initially, the element has been in the hidden state, but the toggle helps to switch between both events.

jQuery toggle() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery Effects - Toggle</h2>
    <p>Click the button to Toggle the content on the page.</p>
    <button>Toggle</button>
    <hr>
    <h3>NEW CONTENT!!!</h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function() {
        $('h3').hide();
        $('button').click(function() {
            $('h3').toggle();
        })
    });
  </script>
</html>

Output:

jQuery effect toggle() method
ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.