How to Get JavaScript Variable Value into CSS

How to get Javascript variable value into CSS?

I'm not sure wether that's the best way to achieve what you want to do, as you could also use a container element and change its content directly:

const screenContentElement = document.getElementById('screen__content'); function pad(value) {  const str = value + '';    return str.length === 2 ? str : '0' + str;}
function clock(){ var d = new Date(); return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());}
setInterval(() => { screenContentElement.innerText = clock();}, 1000);
#screen {  font-family: Arial, sans-serif;  position: relative;  height: 100%;  width: 100%;  background: #98E8EE;  text-align: center;  padding: 2rem 0;}
#screen__content { color: #F9F5F4; font-size: 40px;}
<div id="screen" class="screen">  <span id="screen__content"></span></div>

How to use Javascript variables in CSS?

No, you can not use javascript variables inside css, but you can change the style of an element dynamically via javascript's DOM elements, style property.

document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

In your case:

var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;

//Activates Slowdown
window.onload = loop();

//Speed up
function spin() {
if (speed < 0) {
speed = speed + 10;
loop()
} else {
speed = speed + 10;
}
}

spinner.addEventListener('click', spin);

//Slowdown
function loop() {
setTimeout(
function slow() {
speed = speed - slowSpeed;
document.getElementById("speed").innerHTML = speed;
if (speed > 0) {
loop();
}

document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

}, 1000)
}

//Selectors
function wheel() {
spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}

EDIT:

As per Vladu Ionut's answer , we can use variables in CSS.
Advantages:

  1. It works in modern browsers.

Disadavantage:

  1. It does not work in old browsers like:

    1. IE
    2. EDGE <= 15
    3. Chrome < 49, etc..
      ...
      ...

EDIT:2, Update the code, as per the comment

            var spinnerImg   = undefined;            var speedTxt     = undefined;            var wheelImgUrl  = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";            var spiralImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";             var speed           = 0;            var maxSpeedChange  = 10;            var slowSpeed       = 2;            var speedParam      = slowSpeed;
/** * Function to change the image to wheel * * @Arguments: none * * @Returns: void */ function changeToWheel() { spinnerImg.src = wheelImgUrl; }
/** * Function to change the image to spiral * * @Arguments: none * * @Returns: void */ function changeToSpiral() { spinnerImg.src = spiralImgUrl; }
/** * Function to update speed display * * @Arguments: void * * @Returns: void */ function updateSpeedTxt() { speedTxt.innerHTML = speed; }
/** * @Function to rotate the image * * @Arguments: void * * @Returns: void */ function rotateImg() { spinnerImg.style.transform = "rotate(" + speed + "deg)"; }
window.addEventListener("load", function() { spinnerImg = document.getElementById("spinner"); speedTxt = document.getElementById("speed"); speed = speedParam; setInterval(function() { updateSpeedTxt(); rotateImg(); if (speedParam > slowSpeed) { speedParam -= 0.05; } if (speedParam < slowSpeed) { speedParam = slowSpeed; } speed += speedParam; }, 50);

spinnerImg.addEventListener("click", function() { speedParam += maxSpeedChange; });
});
            #spinner {                width: 500px;                transform-origin: center;            } 
<!DOCTYPE html><html>    <head>     </head>    <body>        <div id="spinnerContainer">            <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/>            <h4 id="speed">N/A</h4>        </div>        <div id="selectors">            <ul>                <button onclick="changeToWheel()">Wheel</button>                <button onclick="changeToSpiral()">Spiral</button>            </ul>        </div>        <footer>
</footer> </body></html>

Javascript variable to css

If you intend to use LESS CSS you can try out this :

    @percent: 1;
@height: `Math.round( screen.height * @{percent})`;
@width: `Math.round( screen.width * @{percent})`;
div.content {
margin: auto;
top: @height;
width: @width;
}

If you intend to use JQUERY you can try out this :

var percent=1;
$("div.content").css('top', Math.round( screen.height * percent)+'px');
$("div.content").width(Math.round( screen.width * percent));

If you intend to use JS you can try out this :

var percent=1;
document.querySelector('div.content').style.top = Math.round( screen.height * percent)+'px';
document.querySelector('div.content').style.width = Math.round( screen.width * percent)+'px';

Access CSS variable from javascript

Just the standard way:

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property
getComputedStyle(element).getPropertyValue('--color-font-general');

Example:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }

How to use JavaScript variable in CSS style?

var color = "#00f";$("#button").click(function(){  $("div").css({"border": "5px solid " + color});});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><button id="button">Add Border</button><div>Hi, I am a div</div>

How can I use a javascript variable in css?

Here's an example solution very similar to your attempt. Notice that I corrected the typo ft to fr in the code snippet. This uses back-tick strings (template literals) for interpolation, but you could also use + to join strings together.

const container = document.querySelector(".container");
//CREATE GRIDfunction grid(size) { container.style.gridTemplateColumns = `repeat(${size}, 1fr)`; for (let row = 0; row < size; row++) { for (let column = 0; column < size; column++) { const square = document.createElement("div"); square.classList.add("square"); container.appendChild(square); } }}
size = prompt("How many squares wide do you want your grid to be?");grid(size);
.container {  display: grid;  width: 500px;  height: 500px;  border: 2px dotted lightgray;}
.container>.square { background-color: white; border: 1px solid black}
<main class="container"></main>


Related Topics



Leave a reply



Submit