skip to Main Content

I’ve been working on a complex animation for our company’s website, but I’m encountering a jittering issue that I can’t seem to resolve. The animation involves a combination of CSS transitions and JavaScript for controlling various interactive elements. When the animation runs, it doesn’t appear smooth and has noticeable jittering, especially on slower devices.

Here’s a simplified version of my code:

document.addEventListener("DOMContentLoaded", function() {
  const container = document.getElementById("animatedContainer");
  const box = document.querySelector(".movingBox");

  container.addEventListener("mouseover", () => {
    box.style.animationPlayState = 'paused';
  });

  container.addEventListener("mouseout", () => {
    box.style.animationPlayState = 'running';
  });

  // Additional JavaScript to control animation with more complex logic
  let animationRunning = true;

  function toggleAnimation() {
    if (animationRunning) {
      box.style.animation = 'none';
      animationRunning = false;
    } else {
      box.style.animation = 'moveBox 5s infinite alternate';
      animationRunning = true;
    }
  }

  document.addEventListener("click", toggleAnimation);
});
#animatedContainer {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

.movingBox {
  width: 50px;
  height: 50px;
  background-color: #3498db;
  position: absolute;
  animation: moveBox 5s infinite alternate;
}

@keyframes moveBox {
  0% {
    left: 0;
    top: 0;
    transform: scale(1);
  }
  50% {
    left: 50%;
    top: 50%;
    transform: scale(1.5);
  }
  100% {
    left: 100%;
    top: 100%;
    transform: scale(1);
  }
}
<div id="animatedContainer">
  <div class="movingBox"></div>
</div>

I’ve tried adjusting the keyframes, the animation duration, and even breaking the animation into smaller parts, but the jitter persists. Could it be an issue with my JavaScript event listeners or how the CSS animations are handled?

2

Answers


  1. Depending on what you mean by jittering, you can add the following CSS:

    .movingBox {
      transform: translateZ(0);
      will-change: transform; 
      animation: moveBox 5s infinite alternate ease-in-out; 
    }
    

    CodePen Link for the solution

    Login or Signup to reply.
  2. Animating by using "left" "right" and "top" "bottom" properties is not very optimized, you should instead try moving the elements with transform: translate() property whenever possible.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search