Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG animation by just adding a class

I created an svg loader animation using SMIL animation. I am showing the svg inside an element by just adding a class name i.e loader.

Fiddle (click on the container to view the loader)

.loader{
    position: relative;
}

/* image */
.loader::before {
    background-image: url('loader.svg');
    /* other properties */
} 

/* blocker */
.loader::after {
    /* other properties */
}

But now, I realized the SMIL is deprecated in chrome. So, I decided to handle animations using CSS. But if I handle animations using css, then I will not be able to manage the code as I am doing above i.e just by adding a class.

If I am using css animations, I need to add a new element inside the container and then use inline-svg concept, IMO.

Is there anyway, I can manage the animation by just adding a class when using css animations?

Some points:

  • I don't want to add any new elements.
  • I will use JavaScript just to add a class and for nothing else.
  • I don't want to generate a gif (a raster image).

I have fiddles for both SMIL and CSS animations:

  • SVG using SMIL animation
  • SVG using CSS animation

I am just limited only to add a class to manage the animation because it keeps my code organised and also I feel it is possible to do so with css animations as well.

like image 515
Mr_Green Avatar asked May 30 '26 19:05

Mr_Green


2 Answers

you can set the css animation in your loader.svg:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <style>
    rect{
      animation:fill 1s linear infinite;
    }

    @keyframes fill{
      0%{
        fill:#f05223;
      }
      100%{
        fill:white;
      }
    }

    rect:nth-child(2){
      animation-delay:.25s;
    }

    rect:nth-child(3){
      animation-delay:.50s;
    }

    rect:nth-child(4){
      animation-delay:.75s;
    }
  </style>
    <rect width="50" height="50" stroke="white" fill="white"></rect>
    <rect x="50" width="50" height="50" stroke="white" fill="white"></rect>
    <rect x="50" y="50" width="50" height="50" stroke="white" fill="white"></rect>
    <rect width="50" x="0" y="50" height="50" stroke="white" fill="white"></rect>
</svg>

https://plnkr.co/edit/tcbdwaSNgadrKYQr5iex?p=preview

like image 152
maioman Avatar answered Jun 02 '26 08:06

maioman


The deprecation notice was quickly reversed in 2016 as much SMIL functionality still has no alternative. It’s not deprecated as of writing this even after 4 years.

like image 20
Robert Monfera Avatar answered Jun 02 '26 08:06

Robert Monfera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!