Home >Web Front-end >JS Tutorial >How to Restart CSS3 Animations Without Removing Elements?

How to Restart CSS3 Animations Without Removing Elements?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 18:16:02794browse

How to Restart CSS3 Animations Without Removing Elements?

Restarting CSS3 Animations: A Better Approach than Element Removal

When working with CSS3 animations, the need to restart an animation upon user interaction can arise. A common scenario is a progress bar that displays the remaining time and requires a reset after completion. While removing and re-inserting the animated element can restart the animation, it involves unnecessary DOM manipulation.

Alternative Method Using Reflow

A more efficient approach involves triggering a browser reflow to apply animation changes. This can be achieved with the following JavaScript function:

function reset_animation() {
  var el = document.getElementById('animated');
  el.style.animation = 'none';
  el.offsetHeight; /* trigger reflow */
  el.style.animation = null;
}

In this example, we select the animated element (#animated) and temporarily set its animation to none. This pauses the animation without resetting its progress. Next, we use offsetHeight to force a reflow, which ensures that all CSS styles are applied. Finally, we set the animation property back to its original value, triggering the animation to restart from its initial state.

Implementation Example

In the following HTML and CSS snippet, we have a progress bar that bounces across the screen:

<div>
#animated {
  position: absolute;
  top: 70px;
  width: 50px; height: 50px;
  background-color: black;
  animation: bounce 3s ease-in-out infinite;
}
@keyframes bounce {
  0% { left: 0; }
  50% { left: calc( 100% - 50px ); }
  100% { left: 0; }
}

Clicking the "Reset" button invokes the reset_animation() function, restarting the animation without any noticeable delay or DOM manipulation overhead.

Conclusion

Using browser reflow to apply animation changes provides a more efficient and elegant solution for restarting CSS3 animations. It eliminates the need for element removal and re-insertion, resulting in a smoother and more performant user experience.

The above is the detailed content of How to Restart CSS3 Animations Without Removing Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn