Cronán Gogarty Cronán Gogarty - 5 months ago 52
CSS Question

Apply random value to animation-duration using jQuery

I have a page that generates 20 randomly sized div elements and places them in random locations within a div container.
Using CSS @keyframe animations I can apply a very simple scale and color animation to each element.

I would like to set the animation-duration CSS property to a random number for each element. I tried to do so using the jQuery.css method like so;

element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime });


but this does not work.

Any suggestions?

The full code is below - example is live at http://codepen.io/CronanGogarty/pen/ZOexMN

.animationContainer {
width: 100%;
min-height: 400px;
height: 100%;
border: 1px solid #000;
overflow:hidden;
}

.animationElement {
position: absolute;
background-color: yellow;
animation: increase infinite;
animation-direction: alternate;
}

@keyframes increase {
0% {
border-radius: 100%;
}

50% {
background-color: orange;
}

100% {
transform: scale(2);
background-color: red;
}
}

$(function () {
createRandomElements();
});

function createRandomElements() {
for (var i = 0; i < 20; i++) {
var dimensions = Math.floor(Math.random() * (60 - 10) + 10);
var width = $('.animationContainer').width();
var height = $('.animationContainer').height();

var eltop = Math.floor(Math.random() * (height - dimensions) + dimensions);
var elleft = Math.floor(Math.random() * (width - dimensions) + dimensions);

var animationTime = Math.floor(Math.random() * (5 - 2 + 1)) + 2;

var element = $('<div>', {
class: 'animationElement',
width: dimensions,
height: dimensions
});
element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime });
element.offset({ top: eltop, left: elleft });
$('.animationContainer').prepend(element);
}
}


As an additional question - can anyone explain why the
overflow:hidden
property isn't working on the .animationContainer element? I suspect it's because the .animationElement divs are being prepended to the container - if anyone has a solution I'd be very thankful.

Answer

The animation-delay and animation-time need to be associated with a unit. Use the following to add an s (seconds) to the value. This makes the css valid.

element.css({
  'animation-duration': animationTime + 's',
  'animation-delay': animationTime + 's'
});

As a bonus, you need to set the animation-container to position: relative if you want its absolutely positioned children to be hidden.

Here's a fork of your pen with the changes.

Comments