📜  jQuery fadetoggle()(1)

📅  最后修改于: 2023-12-03 15:32:08.370000             🧑  作者: Mango

Introduction to jQuery fadetoggle()

jQuery fadetoggle() is a built-in method in jQuery that allows you to fade an element in or out whenever it is clicked. This method is useful when you want to toggle visibility of an element between fade-in and fade-out on clicks.

Syntax

The syntax for jQuery fadetoggle() is straightforward and easy to understand.

$(selector).fadeToggle(speed, easing, callback);
  • selector - The element or elements to be faded in or out.
  • speed - The speed of the fading animation. It can be "fast", "slow", or a specific duration in milliseconds (e.g., 1000).
  • easing - The easing function to be used in the animation (e.g., "linear", "swing", etc.).
  • callback - A function to be executed once the animation is complete.
Example

Here is an example usage of jQuery fadetoggle(). In this example, we have a button that, when clicked, fades a div element toggle between visibility.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery fadetoggle()</title>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#button').click(function(){
        $('#myDiv').fadeToggle();
      });
    });
  </script>
  <style>
    #myDiv {
      width: 200px; 
      height: 200px; 
      background-color: #FF6F61; 
      display: none;
    }
  </style>
</head>
<body>
  <button id="button">Click Me!</button>
  <div id="myDiv"></div>
</body>
</html>

In this example, we first included the jQuery library via a script tag in the head section of our html file. Then, we defined a button with an id of "button" and a div with an id of "myDiv".

Next, we added some CSS styling to our div to make it invisible when the page loads.

We then wrote a script that waits for the document to be ready, and when the button is clicked, the fadeToggle() method is called on the "myDiv" element. This causes the "myDiv" element to fade in or out depending on its current visibility status.

Conclusion

jQuery fadetoggle() is a simple method to use when you want to toggle visibility of an element between fade-in and fade-out on clicks. It has a straightforward syntax that is easy to understand and use, and it can add a nice visual touch to your web pages.