YouTip LogoYouTip

Eff Toggle

## jQuery toggle() Method The `toggle()` method is a built-in jQuery effect method used to toggle between the `hide()` and `show()` states for selected elements. It checks the visibility of the selected elements: * If an element is **hidden**, `toggle()` will run `show()` to make it visible. * If an element is **visible**, `toggle()` will run `hide()` to make it hidden. > **Note:** Hidden elements are completely removed from the page layout flow (equivalent to `display: none` in CSS) and will not occupy any space on the page. --- ## Syntax ```javascript $(selector).toggle(speed, easing, callback); ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `speed` | String / Number | *Optional.* Specifies the speed of the transition effect.
**Possible values:**
- Duration in milliseconds (e.g., `400`, `1000`)
- `"slow"`
- `"fast"` | | `easing` | String | *Optional.* Specifies the speed curve of the animation.
**Default value:** `"swing"`
**Possible values:**
- `"swing"` (slower at the beginning and end, faster in the middle)
- `"linear"` (constant speed throughout)
*Note: More easing functions are available via external plugins.* | | `callback` | Function | *Optional.* A function to be executed after the `toggle()` animation completes. | --- ## Code Examples ### 1. Basic Toggle (No Parameters) Toggle the visibility of all `

` elements instantly when a button is clicked. ```html

This is a paragraph that will toggle between hidden and visible.

This is another paragraph.

``` ### 2. Toggle with Speed Control the duration of the toggle transition using the `speed` parameter (in milliseconds or predefined strings). ```javascript $(document).ready(function(){ // Toggle slowly (600 milliseconds) $("#btn-slow").click(function(){ $("p").toggle("slow"); }); // Toggle with a custom millisecond duration (2000ms = 2 seconds) $("#btn-custom").click(function(){ $("p").toggle(2000); }); }); ``` ### 3. Toggle with Callback Function Execute a custom function immediately after the toggle animation finishes. ```javascript $(document).ready(function(){ $("button").click(function(){ $("p").toggle("slow", function(){ alert("The toggle animation has completed!"); }); }); }); ``` --- ## Technical Considerations * **Display State:** The `toggle()` method changes the CSS `display` property. It restores the element's original display type (e.g., `block`, `inline`, or `inline-block`) when shown, and sets it to `none` when hidden. * **Initial State:** If an element has `display: none` in its inline style or stylesheet, `toggle()` will correctly recognize it as hidden and show it on the first trigger. * **Alternative Signature:** You can also pass a boolean value to the method: `toggle(display)`. If `true`, it shows the element; if `false`, it hides the element. This is useful for conditional toggling.
← Html AddclassEff Stop β†’