Home >Web Front-end >JS Tutorial >How I made toggle transition to
The HTML <details>
element provides a simple way to create expandable and collapsible content sections. Let's explore how to enhance this functionality with smooth CSS transitions, and address the limitations of using CSS alone.
A basic <details>
implementation looks like this:
<code class="language-html"><details> <summary>Click to expand</summary> <p>This is the content.</p> </details></code>
While this works, adding a smooth transition using only CSS proves challenging. The following CSS, for instance, doesn't produce the desired effect:
<code class="language-css">details#my-details { transition-duration: 300ms; }</code>
To achieve a smooth toggle transition, JavaScript is necessary.
The key is to wrap the content within the <details>
element with another element (here, a <div>
). This allows us to target and animate the content separately:
<code class="language-html"><details id="my-details"> <summary>Click to expand</summary> <div> <p>This is the content.</p> </div> </details></code>
The following JavaScript code then handles the animation:
<code class="language-javascript">const details = document.getElementById("my-details"); const summary = details.firstElementChild; const content = summary.nextElementSibling; let isAnimating = false; summary.onclick = (ev) => { ev.preventDefault(); if (isAnimating) return; const contentHeight = content.getBoundingClientRect().height; isAnimating = true; // Closing <details> if (details.open) { return content .animate( { height: [contentHeight + 'px', '0px'] }, { duration: 300 } ) .finished .then(() => details.open = isAnimating = false); } // Opening <details> details.open = true; content.animate( { height: ['0px', contentHeight + 'px'] }, { duration: 300 } ).finished.then(() => isAnimating = false); };</code>
This JavaScript code uses the animate()
method to control the height transition of the content wrapper. Note that in some cases, adding overflow: hidden;
to the content wrapper's CSS may be needed for optimal results.
The JavaScript code prevents the default <summary>
behavior, gets the content height, and then uses the animate()
method to smoothly adjust the height based on whether the <details>
is opening or closing. The isAnimating
variable prevents multiple animations from running concurrently.
The isAnimating
flag ensures that only one animation runs at a time, preventing conflicts and unexpected behavior if the user clicks repeatedly while an animation is in progress.
This technique provides a smooth, controlled transition for the <details>
element. While this example uses height animation, the animate()
method can be adapted to animate other CSS properties, offering a versatile approach to creating engaging user interactions. Remember that a deeper dive into the animate()
method and its capabilities is recommended for more advanced animations.
The above is the detailed content of How I made toggle transition to