Search code examples
javascriptcssvariables

Getting a calc() CSS variable into JavaScript


I am trying to get a CSS variable into Javascript. I have read the other Stack threads pertinent to this goal, but I am still lost. Please save me from myself.

CSS:

:root {
     --loaderSpeed: 100ms; 
     --loaderDuration: calc(var(--loaderSpeed)*44);
    }

JavaScript

setTimeout(() => {
    const box = document.getElementById('loaderWrapper');
    box.style.display = 'none';
 }, 4400);

"4400" needs to be replaced with the variable --loaderDuration

Research indicates that these two are involved:

getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name');

...but I have not been able to successfully implement.

Any ideas, Team? Thank you in advance.


Solution

    • Problem was, you are access root values which returns string.
    • and calc() function cannot calculate multiplication of 100ms * 44 so, I have changed --loaderSpeed:100 removed ms. and also created new valiable called loaderSecondsMultiplier.
    • After that, I have getPropertyValue get css variables values and converted them into a number and then just mutiply them and in last store it in finalTimeout.

    //GETTING DOCUMENT STYLES
    let docStyle = getComputedStyle(document.documentElement);
    // GEETING CSS VARIABLE VALUES
    let loaderSpeed = parseInt(docStyle.getPropertyValue('--loaderSpeed'));
    let loaderSecondsMultiplier = parseInt(docStyle.getPropertyValue('--loaderSecondsMultiplier'));
    // MUTIPLYING AND STORING IT'S VALUE TO finalTimeout
    let finalTimeout = loaderSpeed * loaderSecondsMultiplier;
    setTimeout(() => {
      const box = document.getElementById('loaderWrapper');
      box.style.display = 'none';
    }, finalTimeout);
    :root {
      --loaderSpeed: 100;
      --loaderSecondsMultiplier: 44;
    }
    <div id="loaderWrapper">
      <h1>hey</h1>
    </div>

    Second approach

    let docStyle = getComputedStyle(document.documentElement);
    
    //get variable
    let loaderDuration = docStyle.getPropertyValue('--loaderDuration');
    loaderDuration = loaderDuration.split("ms*");
    loaderSpeed = parseInt(loaderDuration[0].split("( ")[1]);
    console.log(loaderSpeed);
    loaderwheelSpeed = parseInt(loaderDuration[1]);
    
    let value = document.getElementById("value");
    value.innerHTML = `loader Speed: ${loaderSpeed} and loader wheelSpeed: ${loaderwheelSpeed}`
    
    setTimeout(() => {
      const box = document.getElementById('loaderWrapper');
      box.style.display = 'none';
    }, loaderSpeed * loaderwheelSpeed);
    :root {
      --loaderSpeed: 1000ms;
      --loaderDuration: calc(var(--loaderSpeed)*5);
    }
    <div id="loaderWrapper">we are using string split method to extract correct value</div>
    <p id="value"></p>