seany765 seany765 - 3 months ago 9
Javascript Question

CSS animation property in jquery

So I want to generate a random number in JS to concatenate inside the css animation property, so that it has a random time property.

As you can imagine, from my code snippet, this is a preloader. I want it to have a random time (from 2 to 8 seconds long)

$(window).load(function() {

var rnd = Math.random() * (8000 - 2000) + 2000;

$('.progress').css(function() {
"animation": "load" + rnd + "linear"
});

setTimeout(function() {

$('#page').addClass('loaded');
$('#page').removeClass('unloaded');
$('#loader').hide();

}, val);

});

Answer

You're not appending a time unit on your animation duration. You could either assign ms using "animation": "load " + rnd + "ms linear" (see how I'm leaving spaces in between the variable) or you could divide your rnd variable as it's outputting values in thousands and use s through "animation": "load " + rnd/1000 + "s linear".

If this doesn't work, please provide a MCV example and we will help you further.

EDIT: Check this, I've updated your code snippet. The problem was that .css( property, value) and not a function as you sent.

$(window).load(function() {

  var rnd = Math.random() * (8000 - 2000) + 2000;

  $('.progress').css("animation", "load " + rnd + "ms linear");

  setTimeout(function() {

    $('#page').addClass('loaded');
    $('#page').removeClass('unloaded');
    $('#loader').hide();

  }, rnd);

});
#page {
  position: absolute;
  background: rgb(240, 240, 240);
  height: 100%;
  width: 100%;
}

#loader {
  position: absolute;
  top: calc(50% - 10px);
  left: calc(25%);
  width: 50%;
}

.progress {
  width: 100%;
  height: 20px;
  background: #3498db;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

.loaded {
  opacity: 1;
}

.unloaded {
  opacity: 0;
}

@keyframes load {

  0% {
    width: 0%;
  }

  25% {
    width: 50%;
  }

  50% {
    width: 60%;
  }

  90% {
    width: 95%;
  }

  100% {
    width: 100%;
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loader">
  <div class="progress"></div>
</div>

<div id="page" class="unloaded">
Loaded result
</div>