📜  jquery slidetoggle - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:11.609000             🧑  作者: Mango

jQuery Slidetoggle - Javascript

Introduction

jQuery Slidetoggle is a Javascript method provided by the jQuery library. It allows you to create interactive and dynamic sliding effects on elements in your web page. With jQuery Slidetoggle, you can toggle the visibility of elements with a sliding animation, adding an enhanced user experience to your website.

Usage

The jQuery Slidetoggle method is used to hide or show elements with a sliding animation. It works by adjusting the height of the element, gradually revealing or hiding its content.

Syntax
$(selector).slideToggle(speed, [callback]);
  • selector: It specifies the element(s) to apply the slideToggle effect to.
  • speed: It specifies the speed of the animation. It can be in milliseconds, or you can use the keywords "slow" or "fast" to indicate predefined durations.
  • callback (optional): It is a function to be executed after the slideToggle animation completes.
Examples

Example 1: Basic Usage

In this example, we'll use the slideToggle() method to toggle the visibility of a div element with an id of "content". Initially, the content is hidden, and clicking the "Toggle" button will slide it down to reveal the content.

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

<button id="toggleBtn">Toggle</button>
<div id="content" style="display: none;">
    This is the content to be toggled.
</div>

<script>
$(document).ready(function() {
    $("#toggleBtn").click(function() {
        $("#content").slideToggle();
    });
});
</script>

Example 2: Custom Speed and Callback

In this example, we'll use a custom speed of 2000 milliseconds and specify a callback function to be executed after the slideToggle animation completes. The callback function will display an alert message.

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

<button id="toggleBtn">Toggle</button>
<div id="content" style="display: none;">
    This is the content to be toggled.
</div>

<script>
$(document).ready(function() {
    $("#toggleBtn").click(function() {
        $("#content").slideToggle(2000, function() {
            alert("SlideToggle animation completed!");
        });
    });
});
</script>
Conclusion

jQuery Slidetoggle is a powerful method that allows you to easily add sliding effects to your web page elements. By toggling the visibility of elements with smooth animations, you can enhance the user experience and create dynamic content interactions.