Using JQuery to animate CSS properties

I'm looking to create a unique effect in JavaScript where I can generate a random number to use in a CSS animation property. Specifically, I want this for a preloader that will have a randomized duration between 2 and 8 seconds.

As you'll see in the code snippet below, I am using jQuery to achieve this. The goal is to dynamically set the animation time based on the random number generated.

$(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);

});

Answer №1

Make sure to include a time unit for your animation duration. You have two options: either add ms by using

"animation": "load " + rnd + "ms linear"
(notice the spaces between the variables) or divide your rnd variable by 1000 since it outputs values in thousands and use s with
"animation": "load " + rnd/1000 + "s linear"
.

If these solutions don't work, please provide a [MCV example](https://stackoverflow.com/help/mcve) so we can assist you further.

UPDATE: I've made changes to your code snippet. The issue was with the usage of .css( property, value) instead of a function as you had initially 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for minimizing the padding/space between dynamically generated div elements using html and css

Currently, I have 4 dropdown menus where I can choose various options related to health procedures: Area, specialty, group, and subgroup. Whenever I select a subgroup, it dynamically displays the procedures on the page. However, the issue I am facing is th ...

CSS-only countdown animation

I've been experimenting with a pure HTML/CSS countdown animation, but I'm facing challenges in getting it to run smoothly. Currently, I'm focusing on minutes and seconds only. One issue I encountered is that the digit representing tens of mi ...

Exploring and Presenting Database Findings (PHP MySQL) in a Format Beyond Traditional Tables in HTML

My code is functioning as intended, where a search is performed in the table based on user input, displaying the attributes within an HTML table. For a clearer picture, I will provide an image of the search output: Output of the Search However, due to the ...

Creating an Angular 7 Template using HTML CSS and Javascript

I recently acquired a template that comes with HTML, CSS, and Javascript files for a static webpage. My goal is to integrate these existing files into my Angular project so I can link it with a Nodejs application to create a full-stack webpage with backend ...

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...

Create a dynamic webpage using HTML and CSS that utilizes hover effects to show and hide text and images

Struggling to find a way to achieve this inline. Normally, you would hide a child and target the parent for display... <p class="demo_text">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in ...

Paper.js - generate a collection of movable shapes

I am attempting to use paper.js to create draggable shapes where the index of each shape is provided during dragging. Unfortunately, I keep encountering an error that says "Uncaught TypeError: Cannot read property 'position' of undefined". If a ...

Issues with executing href JavaScript in a Tampermonkey script

I am in the process of creating a script that will adjust the display property of a <td> element. Here is what I have so far: // ==UserScript== // @name Dema VOC hide // @version 0.1 // @include http://mywebsite.com/* // @require ...

What is the correct method for accessing and reading each line in a file using node.js and jade?

Just starting out with Node.js and I'm looking to open a file and read each line. Can anyone provide guidance? Here's the code snippet, which can be implemented in Ruby (html.erb format). <% File.open("/home/ubuntu/test.text", "r").each_line ...

Web worker causing issues with loading buffer geometry mesh

After converting my geometry to buffer geometry and successfully creating a mesh with both the geometry and material, I encountered an issue where the model is not displaying in the window. Below is the code snippet: var myWorker = new Worker("js/respond ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

Tips on creating unit tests for AngularJS attribute-type directives using Jasmine

I have a directive that doesn't use any template or templateUrl. How can I write a unit test for this directive? Below is the code for my directive. var app = angular.module('SampleDirective'); app.directive('sampleContent', [fun ...

What could be the reason for my new course not being recognized?

Looking to modify the behavior of a button where, when clicked, it hides a specific div element, changes its text display, and toggles between classes using addClass/removeClass for subsequent click events. Unfortunately, the intended functionality is not ...

Problem Encountered with Navigation Bar following the Cloning and File Transfer in a React (Next) Project

I cloned the repository and transferred the files using these commands: 1. git clone https://github.com/adrianhajdin/portfolio.git 2. cd portfolio 3. mv * .. Upon executing npm run dev, everything appears fine, but upon clicking on the About button or ...

Why is JavaScript unable to fetch JSON data from C when the uint32 value is a multiple of 256 plus 10?

After receiving some helpful feedback, I decided to make some changes to this question that I posted yesterday. The title and content have been edited for clarity based on the new information I've learned. Recently, I've been utilizing C code to ...

Shading rows based on a specific field value in the Angular UI Grid

Is it possible to color rows based on their field values in the latest angular-ui-grid when all columns are generated dynamically and row selection is enabled? I have come across suggestions to use a rowTemplate for this purpose. Here is an example of a r ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Every time the page is refreshed, the value stored in React localStorage gets

After adding a new item to the list, the local storage gets updated. However, upon page refresh, I noticed that the key remains but the value is reset to an empty array. import { useState, useEffect } from 'react'; function App() { const [data ...

Working with JSON parsing in AngularJS without a specified element name

I am looking to extract data from a JSON response containing Country & State information. Here is the URL for the JSON data: { "China": [ "Guangzhou", "Fuzhou", "Beijing", "Baotou", "Hohhot", "Guiyang", "Yinchuan", "Nanjing", "Changzhou", "Chuzhou" ...