I'm trying to create an animated background. In short, there are 6 icons which should all animate to move around the page within a small boundary.
Current JS Fiddle works to an extent but need to make amends as below:
https://jsfiddle.net/mLegg2vt/7/
I wish to randomly generate the movement of these icons so that they bob/hover around within the following bounds:
x axis = 1px to 5px
y axis = 13px to 20px
I have managed to get a solution using hardcoded values but now think I'm going about it the wrong way as it would require creating multiple keyframe animations for each icon with different values. I'm not necessarily against this, but I'm not sure how to achieve it.
I have generated random numbers for each icon within the bounds above using the following:
var x = randomInt(5, 1); // use this value for x in translate3d
var y = randomInt(20, 13); // use this value for y in translate3d
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
However I now need to create a keyframe animation for this particular icon using the values created above. At present my hardcoded keyframe animation is used for all icons and looks like this:
@keyframes gentleHover {
0% {
transform: translate3d(0px, 0px, 0px);
}
50% {
transform: translate3d(5px, 15px, 0px);
}
100% {
transform: translate3d(0px, 0px, 0px);
}
}
In the above, I wish to populate the 50% keyframe with my values e.g:
50% {
transform: translate3d(xpx, ypx, 0px);
}
Now my question is how can I do this for each icon, within jQuery? How can I create a CSS keyframe for each of these 6 icons, with the values? I understand how to add CSS to a particular element with .css() but now how to create an entirely new piece of CSS within the stylesheet. I understand I'll then need to add that generated keyframe animation onto this element, but that's easy:
$(this).css('animation', '[theCreatedKeyframeHere] 5s linear infinite');
The only way I can think to do this is to put the keyframes wrapped inside <style> tags into the stylesheet. But is that recommended?
It's also important to note all the jQuery above is included in a site.js file which is called in via the header. It is not in <script> tags on the page.