The toggle() Effect is a combination of Hide and Show effect. i.e. Hides the visible element and if the element is hidden, makes it visible.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p> This is a sentence </p> <button> Show/Hide </button> <script> $('button').click( function() { $('p').toggle(); }); </script> </body> </html>
So, in the above example, we have a <p> element,
<p> This is a sentence </p>
And a <button> element,
<button> Show/Hide </button>
And on buton click, the JQuery action gets triggered,
$('button').click( function() { $('p').toggle(); });
And the toggle() effect gets triggered. So if the <p> element is hidden, it shows it and it the <p> element is visible, it hides it.
Similarly, you can use the speed and callback function with toggle() effect.
Now, what if you want the <p> element to be hidden and shown slowly. And there is a second parameter that determines the speed as in how to hide the element. It could be fast, slow or milliseconds.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p> This is a sentence </p> <button> Show/Hide </button> <script> $('button').click( function() { $('p').toggle(1000); }); </script> </body> </html>
So, there is this parameter in toggle() effect that determines that how slowly the element would be hidden.
Now, let's say, you want to display a message, stating the element is hidden. You can achieve it using a callback function.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p> This is a sentence </p> <button> Show/Hide </button> <script> $('button').click( function() { $('p').toggle(1000, function() { alert("The effect is completed") }); }); </script> </body> </html>
So, in the above JQuery statement,
$('button').click( function() { $('p').toggle(1000, function() { alert("The effect is completed") }); });
Along with the toggle() effect, we have used the hide speed as the first parameter and callback function as the second parameter.
Now, if you see the callback function,
function() { alert("The effect is completed") }
It displays an alert,
alert("The effect is completed")