Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads.

Here is the JavaScript code:

var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var start= rootStyles.getPropertyValue('--start');
var finish= rootStyles.getPropertyValue('--finish');
//function that provides data for these values
root.style.setProperty('--start', +storedelo-300);
root.style.setProperty('--finish', +storedelo);

And here is the CSS code:

:root {
    --start: 0;
    --finish: 0; 
  }
@property --num {
    syntax: "<integer>";
    initial-value: 0;
    inherits: false;
  }
  
 div {
   transition: --num 5s;
   --num: var(--start);
   counter-set: num var(--num);
 }
 div::after {
   content: counter(num);
 }
 div::hover {
   --num: var(--finish);
 }

Additionally, the @keyframes rule seems to not be working properly for some reason:

@keyframes counter {
  from {
    --num: var(--start);
  }
  to {
    --num: var(--finish);
  }
}

Answer №1

To ensure that the initial CSS variables values are set correctly, consider creating a function for this purpose. This function can be invoked on either the DOMContentLoaded event of the window (MDN documentation) or the load event of the window (MDN Documentation).

var root = document.querySelector(":root");
var rootStyles = getComputedStyle(root);
var start = rootStyles.getPropertyValue("--start");
var finish = rootStyles.getPropertyValue("--finish");

function updateCounterValues() {
  root.style.setProperty("--start", +storedelo - 300);
  root.style.setProperty("--finish", +storedelo);
}

window.addEventListener("DOMContentLoaded", (event) => {
    updateCounterValues();
});

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

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center p ...

Ways to transition to the subsequent page in Selenium WebDriver following the click of the submit button

After successfully automating the process of filling in a textbox and clicking the "proceed with booking" button using a submit() command, I encountered an issue. The HTML code does not provide a URL that can be used in the driver.get([url]) method to navi ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

Compass - substitute a single value for an alternate attribute

Can I utilize a value from one class to customize another? Consider the following class: .sourceClass { color: red; } And now, let's say we have this class: .destinationClass { border-color: ###needs to match the color in .sourceClass => re ...

Tips for maintaining authentication in a Next.js application with Firebase even when tokens expire or the page is refreshed

Struggling with firebase authentication flows while building an app using firebase and next.js. Everything was going smoothly until I encountered a bug or error. When my computer remains logged in to the app for some time and I refresh the page, it redirec ...

Tips for keeping a label above an input field

Is it possible to add a styled label on top of an input element? I have seen images placed inside input elements for indicating the type of input accepted. For example, in a login form, a user icon represents the username field and a key icon represents th ...

Challenges with displaying the appropriate user interface in the dashboard according to different roles

My current project involves rendering different UI components based on selected roles such as brands, agency, or influencer. However, despite my efforts to implement the logic for this functionality, the correct UI is not being loaded and I'm struggli ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Contrast between the expressions '$(<%= DDL.ID %>) and $('<%= DDL.ID %>')

I spent hours trying to attach an event to a drop-down list with no success. I even sought help in a JavaScript chat room, but couldn't find a solution. However, by randomly attempting the following code: $('<%= ddl.ID %>').bind(&apos ...

What is the best method for transforming a base64 encoded string into a base64 formatted PDF string?

Could someone please help me with a problem I'm facing? I am utilizing an AngularJS .pdf viewer that displays documents in a modal using base64. Everything works smoothly when the base64 is generated from a .pdf file. The backend (Java) generates th ...

Checking for undefined values in fields within an array of objects using scenarios in JavaScript

I am encountering an issue with checking for undefined and empty strings in an object array using Javascript. The code provided is partly functional, but I have hit a roadblock. Within the array object, If the field value is undefined or empty, it should ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

Securing paths in NuxtJS

Hey there! I'm just getting started with nuxt and have set up the following routes: /home /dashboard /login My goal is to secure the /dashboard route only for users who are logged in and have a token stored in LocalStorage. The simplest solution ...

What is the best way to adjust the spacing between components to prevent overlapping?

I'm looking to adjust the spacing between the textfield and button components so they don't overlap. I want to create some space between them but I'm not sure how to achieve this. I'd like to have at least 1-2 spaces added between the ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

Locate an item based on the `Contains` criterion by utilizing Express and Mongoose

Looking to find items in my collection that have userName containing adm. Expecting 2 results based on having records with userNames like admin0 and admin2, but the search returns nothing. The query being used is: Person .find({ userName: { $in: &a ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...