How do I start counter on load? I was able to make it start on hover but never get it to work on load.
JS:
var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var start= rootStyles.getPropertyValue('--start');
var finish= rootStyles.getPropertyValue('--finish');
//function witch gives data for this values
root.style.setProperty('--start', storedelo-300);
root.style.setProperty('--finish', storedelo);
CSS:
: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);
}
And @keyframes is not working for some reson
@keyframes counter {
from {
--num: var(--start);
}
to {
--num: var(--finish);
}
}
CodePudding user response:
You can create a function to set the initial CSS variables values and then call it on window DOMContentLoaded
(MDN documentation) or window load
MDN Documentation
var root = document.querySelector(":root");
var rootStyles = getComputedStyle(root);
var start = rootStyles.getPropertyValue("--start");
var finish = rootStyles.getPropertyValue("--finish");
//function witch gives data for this values
function startCounter() {
root.style.setProperty("--start", storedelo - 300);
root.style.setProperty("--finish", storedelo);
}
window.addEventListener("DOMContentLoaded", (event) => {
startCounter();
});