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

Error encountered in AngularJS when utilizing the Flickr API with the parameter "nojsoncallback=1": Unexpected token Syntax

My AngularJS application is trying to access the Flickr API. I need the data in RAW JSON format without any function wrapper, following the guidelines provided in the documentation by using &nojsoncallback=1. However, I keep encountering a console er ...

Discover the method for retrieving information through AJAX requests and dynamically displaying or hiding content based on the received

Currently, I'm in the process of developing a PHP script that outputs a numerical value indicating the number of unread messages. The snippet below showcases my code that triggers the PHP function every 30 seconds: setInterval(function (){ ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Unable to establish a breakpoint in a source-mapped file (illustrated using jQuery)

Having trouble setting a breakpoint on a minified JavaScript source file that is mapped to real sources using a source map file. An example of this problem can be seen on the website jquery.com. On this particular site, the imported script is jquery.min. ...

Comparison: JavaScript Cookies vs PHP Cookies

I have been trying to implement the following code: JS: Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 }); PHP: $cookie_str = $post_id.'_'.get_client_ip(); if (isset($_COOKIE[$cookie_str_]) ){ print_r ...

Can you clarify the distinction between calling subscription.unsubscribe() and subscription.remove()?

Currently, I am working with Angular 5 and have successfully subscribed to an observable with the use of the subscribe() method. My concern pertains to whether simply calling the unsubscribe() method on the subscription will be adequate for cleaning up all ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...

Utilizing property validation in your codebase

How can I set up my code to display a warning in the console if the value of the Prop is not a string? The player-name prop should always be a string. If this: <greet :player-name="5"></greet> contains a number, I want my code below to generat ...

Is it possible to conceal the mapbox access token during the map initialization process?

I have successfully integrated the mapbox API to create an interactive map on my website. To ensure the security of my access token, I have set up a proxy to handle the API requests externally. However, I am facing a challenge when it comes to hiding the a ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

What strategies can be used to effectively manage multiple asynchronous requests?

I have two requirements: one is to load an image (which will take a long time on the backend server), and the other is to perform an AJAX request. I would like it to be structured like this: $.when( [perform image loading] [perform ajax request] ).t ...

Setting a port in Next.js: A step-by-step guide

I have one application currently running on port 3000 and I need to run another application on a different port in React Next.js. How can I make this change? In my package.json file, the current scripts section looks like this: "scripts": { & ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

Guide to exporting several Chart.JS graphs to a PDF document with each graph on a separate page

I am currently utilizing the JavaScript code provided below to generate a pdf file containing multiple charts. However, all the charts are being placed on a single page. My inquiry is regarding how I can customize the code to have each chart on its own sep ...

Special html effects for scrolling

Recently, I've been noticing a trend of websites incorporating new and innovative scrolling effects. One great example is: As you scroll down the page, the initial section stays fixed in place (z-index of 1?) while the content scrolls over it seamles ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

How can I effectively set up and utilize distinct npm modules on my local environment?

A React Native component I have created lives in a separate folder with its own package.json file, and now I want to use it in another project. The component named MyComponent is located in Workspace/MyComponent and has specific dependencies listed in its ...

Hide the border below the active tab

Could anyone assist me in removing the border below the selected tab? I've attempted multiple approaches without success. I experimented with adding a negative margin to the tab and creating a white border, but as the border I want to conceal is from ...

The failure to build was due to the absence of the export of ParsedQs from express-serve-static-core

Encountered the error message [@types/express]-Type 'P' is not assignable to type 'ParamsArray'. Resolved it by installing specific packages "@types/express": "^4.17.8", "@types/express-serve-static-core": ...

Why does the Leaflet map appear inconsistently?

It's baffling that Firefox 24.0 and the latest Chrome are both failing to load my Leaflet map, but surprisingly, it works perfectly on Safari on my iPhone. Quite an interesting dilemma. This is my initial attempt at using Leaflet and Bootstrap...ever ...