John Smith
John Smith

Reputation: 601

SVG animation works when style is set programmatically but not when only using a stylesheet

I have a svg document which contains a stylesheet. Using the stylesheet I can set the fill of a rect (The stylesheet is working). What I'm trying to do is to set a color changing animation. I have the following stylesheet:

@keyframes blinking-effect {
    0% {
        stroke: rgba(255, 255, 0, 1);
        fill: rgba(0, 220, 0, 1);
    }
    100% {
        stroke: rgba(255, 255, 255, 0);
        fill: rgba(0, 0, 220, 1);
    }
}
.animation {
    animation-name: "blinking-effect";
    animation-duration: "0.5s";
    animation-iteration-count: "infinite";
    animation-timing-function: "ease-in-out";
    animation-direction: "alternate";
}


<rect id="rect1" x="0" y="0" width="50%" y="50%" class="animation " />

I do not know why this doesn't work. However it does work when I execute the following code:

document.getElementById("rect1").style.setProperty("animation-name", "blinking-effect");
document.getElementById("rect1").style.setProperty("animation-duration", "0.5s");
document.getElementById("rect1").style.setProperty("animation-iteration-count", "infinite");
document.getElementById("rect1").style.setProperty("animation-timing-function", "ease-in-out");
document.getElementById("rect1").style.setProperty("animation-direction", "alternate");

Is there a way to do this without using JavaScript?

Upvotes: 2

Views: 127

Answers (2)

Robert Longson
Robert Longson

Reputation: 124169

Lose the quotes on the CSS.

.animation {
    animation-name: blinking-effect;
    animation-duration: 0.5s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
    animation-direction: alternate;
}

Also by the by the rect has repeated y attributes and no width which I assume is a typo and the animation class attribute ends in a space which I assume is another typo.

Upvotes: 1

Weafs.py
Weafs.py

Reputation: 22992

Do it this way.

.animate {
  -webkit-animation: blinkingEffect 0.5s infinite ease-in-out alternate;
  animation: blinkingEffect 0.5s infinite ease-in-out alternate;
}
@-webkit-keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
@-moz-keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
@keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
<svg width="50" height="50" viewBox="-1 0 51 51">
  <rect class="animate" id="rect1" x="0" y="0" width="50" height="50" />
</svg>

Upvotes: 1

Related Questions