joebean joebean - 7 months ago 43
HTML Question

Css animation random delay

I'm trying to build a webpage for a comic studio and I want one of the characters to come in from the side every so often. So far I have this in the css

.charc {
animation:peek 20s infinite;
left:-500px
}

@-webkit-keyframes peek{
1% {transform:translateX(-500px)}
10%{transform:translateX(100px)}
20% {transform:translateX(-200px)}
100% {transform:translateX(-500px)}
}


and the html

<img src="character.jpg" class="charc"/>


This means the character comes on over and over again. I don't know whether it is possible to get random figures in CSS but I thought if it is, You guys would know

p.s. I know this will only work in chrome but I will be changing that soon.

Answer

You need to use js/jQuery for that.

    function move() {
      $('.charc')
        .animate({
          left: '-500px'
        }, 200)
        .animate({
          left: '100px'
        }, 400)
        .animate({
          left: '50px'
        }, 400)
        .animate({
          left: '-500px'
        }, 100, function() {
          var nextIn = Math.floor(Math.random() * 1000);
          setTimeout('move()', nextIn);
        })
    }

    $(document).ready(function() {
      move();
    });
#scene {
  width: 500px;
  height: 100px;
  border: 2px solid black;
  margin: 20px;
}
.charc {
  position: absolute;
  left: -500px;
  top: 20px;
  width: 20px;
  height: 20px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scene">
  <div class="charc"></div>
</div>