1.21 gigawatts
1.21 gigawatts

Reputation: 17796

Fade the same image in and out in one line of CSS automatically

I have an image that I want to fade in and out automatically. I've read about transitions and animations and would like to use one or two styles (not style declarations). It's OK to start the animation via JavaScript.

In this example on MDN you can see that the items are animated on page load by switching classes. I would like it to be simpler than that.

Here is what I have so far and it seems like it should work but it's not.

function updateTransition(id) {
  var myElement = document.getElementById(id);
  var opacity = myElement.style.opacity;
  if (opacity==null || opacity=="") opacity = 1;
  myElement.style.opacity = opacity==0 && opacity!="" ? 1 : 0;
}

var id = window.setInterval(updateTransition, 5000, "myElement");
updateTransition("myElement");
#myElement {
    background-color:#f3f3f3;
    width:100px;
    height:100px;
    top:40px;
    left:40px;
    font-family: sans-serif;
    position: relative;
    animation: opacity 3s linear 1s infinite alternate;
}
<div id="myElement"></div>

Also, here is an example of an animation on infinite loop using a slide animation (3 example in the list). I'd like the same but with opacity.

https://developer.mozilla.org/en-US/docs/Web/CSS/animation

The linked question is not the same as this. As I stated, "single line styles (not style declarations)".

Upvotes: 1

Views: 707

Answers (2)

Aziz.G
Aziz.G

Reputation: 3721

You can use animation-iteration-count :

#myElement {
  background-color: #f3f3f3;
  width: 100px;
  height: 100px;
  top: 40px;
  left: 40px;
  font-family: sans-serif;
  position: relative;
  animation: slidein 2s linear alternate;
  animation-iteration-count: infinite;
}

@keyframes slidein {
  0% {
    opacity: 0;
    left: -100px;
  }
  50% {
    opacity: 1;
    left: 40px;
  }
  100% {
    opacity: 0;
    left: -100px;
  }
}
<div id="myElement"></div>

Upvotes: 1

nloewen
nloewen

Reputation: 1299

What you need is to define your animation using keyframes. If you are trying to apply multiple animations, you can provide a list of parameters to the animation CSS properites. Here's an example that applies a slide in and fade animation.

.fade {
  width:100px;
  height:100px;
  background-color:red;
  position:relative;
  animation-name:fadeinout, slidein;
  animation-duration:2s, 1s;
  animation-iteration-count:infinite, 1;
  animation-direction:alternate, normal;
}

@keyframes fadeinout {
  0% {
    opacity:0
  }

  100% {
    opacity:100
  }
}

@keyframes slidein {
  from {
    left:-100px;
  }
  
  to {
    left:0px;
  }
}
<div class='fade'>

</div>

Upvotes: 2

Related Questions