Cover Image for jQuery toggle() method
89 views

jQuery toggle() method

The jQuery toggle() method is used to toggle the visibility of selected elements. It allows you to show or hide elements alternately with a single method call. When called on a hidden element, it will be displayed, and when called on a visible element, it will be hidden.

The syntax for using the toggle() method is as follows:

$(selector).toggle();
  • selector: It is a string that specifies the elements to be selected.

Here’s an example of how you can use the toggle() method:

HTML:

<div id="myDiv" style="display: none;">
  <p>This is some hidden content.</p>
</div>
<button id="toggleButton">Toggle Content</button>

JavaScript:

// Attach a click event handler to the button
$('#toggleButton').click(function() {
  // Toggle the visibility of the div
  $('#myDiv').toggle();
});

In the example, when the button with the ID “toggleButton” is clicked, the toggle() method is used to toggle the visibility of the div element with the ID “myDiv.”

If the div is hidden (with “display: none;”), it will become visible. If the div is already visible, it will be hidden.

The toggle() method is commonly used to create toggle effects for elements, such as showing and hiding content when a user clicks a button or triggering animations that toggle the visibility of an element on the page.

Please note that the toggle() method is deprecated as of jQuery version 1.8 and removed in jQuery 3.0. It is recommended to use separate methods like show() and hide() or the fadeToggle() and slideToggle() methods to achieve similar toggle effects. These methods provide more control over the animations and are still supported in the latest versions of jQuery.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS