Reputation: 128
I'm creating a simple game using Javascript, Css and Html. And i created a javascript function that generate random number from 3 to 15 then it add an 's' to make the result like (15s) to use it like an animation-duration in css.
I've google it but i didn't find the sample.
Js Code :
function rand() {
var min=3;
var max=15;
var random = Math.random() * (+max - +min) + +min;
var time = random+'s';
return time;
}
Css code:
.enemy {
position: relative;
right:300px;
animation-name:move;
animation-duration:(the rand() function here);
}
Upvotes: 0
Views: 1189
Reputation: 10879
IE once supported CSS expressions, but they were deprecated long ago and not supported by other browsers. You can set the value via JS like this:
document.querySelector('.enemy').style.animationDuration = rand() + 's';
Of course, you'll have to do this every time the content changes (i.e. when adding an element with the enemy class), you'll probably want to do this for all possible elements using querySelectorAll()
instead and iterating over them, handle the case when no such element exists (thus returning null
) etc.
A short example based on https://www.w3schools.com/css/tryit.asp?filename=trycss3_animation3
function rand() {
var min=3;
var max=15;
var random = Math.random() * (+max - +min) + +min;
var time = random+'s';
return time;
}
var randomDuration = rand();
console.log('animation duration: ' + randomDuration);
document.querySelector('.enemy').style.animationDuration = randomDuration;
.enemy {
width: 100px;
height: 100px;
background-color: red;
position: relative;
-webkit-animation-name: example; /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
animation-name: example;
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
/* Standard syntax */
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
<div class="enemy"></div>
Upvotes: 2