2

I'm trying to change the animation-duration attribute randomly (from 0 to 1) in the below css code.

@keyframes blink {
   50% { border-color: #ff0000; }
}
p{
    animation-name: blink ;
    animation-duration: 0.1s ;
    animation-timing-function: step-end ;
    animation-iteration-count: infinite ;
    animation-direction: alternate ;
}

HTML

<div id="label_div">
    <p id="label" class = "blink">Player #</p >
</div>

No Javascript used so far and I am open to use it. Any idea on how to do that? I had a look on this question but I couldn't figure out how to solve my problem.

Community
  • 1
  • 1
Joseph Wahba
  • 660
  • 3
  • 9
  • 25

2 Answers2

3

your Animation is not working for me but I think this should work

const label = document.querySelector("p");
label.style.animationDuration = Math.random() + "s";

Math.random() will return a number between 0-1. http://www.w3schools.com/jsref/jsref_random.asp

btw to fix your animation just add border: solid #000; to your p css

MennyMez
  • 2,426
  • 18
  • 18
1

Determine a random number between 0 and your upper time-limit using:

var rnd = Math.Random() + UPPERLIMIT;

Put that code in a function, and make it execute itself after the calculated random delay:

function randomTimer(){
    var rnd = Math.Random() + UPPERLIMIT;
    setTimeout(randomTimer, rnd);
}

Then, just make sure to apply the delay to your element every cycle.

function randomTimer(){
    var rnd = Math.Random() + UPPERLIMIT;
    var el = document.querySelector("p");
    el.style.animationDuration = rnd + "s";
    setTimeout(randomTimer, rnd);
}

This will cycle your animation with a randomized duration every time.

FvB
  • 713
  • 6
  • 15