How To Animate SVG With Vanilla JS

To animate an SVG stroke with vanilla JS without using an ID, you can use the querySelectorAll() method to select all the SVG path elements that you want to animate. Then you can use a forEach loop to iterate over the selected path elements and apply the animation to each one.

Here’s an example code snippet that uses the stroke-dasharray and stroke-dashoffset properties to create a dash animation effect.

Example with duration 5000 ms:

The setup in Bricks:

Replace your own svg element. This is just example svg element with black stroke:

<svg viewBox="0 0 100 100">
  <path d="M10 10 L90 90" stroke="black" stroke-width="4" fill="none"/>
  <path d="M90 10 L10 90" stroke="black" stroke-width="4" fill="none"/>
</svg>

Copy and paste below JS code to code block. Make sure wrap with <script> tag.

const paths = document.querySelectorAll("svg path");

paths.forEach((path) => {
  const length = path.getTotalLength();

  path.style.strokeDasharray = length;
  path.style.strokeDashoffset = length;

  path.animate(
    [{ strokeDashoffset: length }, { strokeDashoffset: 0 }],
    {
      duration: 1000, //Adjust your desire duration here
      easing: "linear",
      fill: "forwards",
    }
  );
});

In this example, we first get all the path elements in the SVG using querySelectorAll(). Then we iterate over each path element using forEach and get the total length of each path using the getTotalLength() method.

We then set the stroke-dasharray property to the length of the path, which creates a dashed line with the same length as the path. We also set the stroke-dashoffset property to the same length, which hides the dashed line behind the path.

Finally, we use the animate() method to animate the strokeDashoffset property from the path’s total length to 0 over a duration of 1000 milliseconds with a linear easing function. The fill: "forwards" property ensures that the animation remains at its final state after it completes.

Leave comment or code correction