Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Javascript variables in CSS?

Im trying to make an image spin when you click it. The more you click it the faster it spins, and if you stop clicking it will slow down over time.

The problem is that the only way to spin an object without jQuery is with the "transform" property in CSS (What I know of at least). Is there any way to use JavaScript variables in CSS? Or is there another way to spin my image? Or will I need to use jQuery?

Code:

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();
      }
    }, 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";
}
#spinner {
  width: 500px;
}
#spinner {
  transform: rotate("speed"deg);
}
/* The "speed" is the variable I want to use from the JavaScript */ 
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
  </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="wheel()">Wheel</button>
        <button onclick="spiral()">Spiral</button>
      </ul>
    </div>
    <footer>

    </footer>
    <script src="script.js"></script>
  </body>
</html>
<!-- END -->
like image 434
nan Avatar asked Nov 29 '22 08:11

nan


2 Answers

You can declare variables in css (See the specifications--> https://www.w3.org/TR/css-variables/)

:root {
  --deg: 10deg;
}

and then you can use it

#spinner {
  transform: rotate( var(--deg));
}

How to access variables with JavaScript

get

var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var deg= rootStyles.getPropertyValue('--deg');
console.log(deg); 
--> 10deg

set

root.style.setProperty('--deg', '20deg');

Currently, 88 percent of global website traffic supports CSS Variables

like image 159
Vladu Ionut Avatar answered Dec 09 '22 19:12

Vladu Ionut


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>
like image 33
Dinesh Patra Avatar answered Dec 09 '22 19:12

Dinesh Patra