Home > OS >  How to use variable from javascript in inline css?
How to use variable from javascript in inline css?

Time:12-14

Trying to call the "color" variable for use in the inline css. I'll replace the "red" output with a function but I need to know how to do this first. Thanks

Code: `

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            var color = "red"
        </script>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
        <title>New Tab</title>
        <style>
            .fit {
                max-height: 99vh;
                max-width: 99%;             
            }
        </style>
    </head>
        <body style="color: black" scrolling="no">
            <div  >
                <div style= "text-align: center;">
                    <div id= "someInput" style= "background-color: color;">
                        <img class= "fit";  id="img1" id="i" src="" style= ""/>
                    </div>
                </div>
              
                
    <script src="/randomthing.js"></script>
    <script src="/randomthing2.js"></script>
    <script src="/jquery.3.4.1.js"></script>
    <script src="/background.js"></script>
    
    </body>
</html>

`

Tried to look at other forums but didn't find any solution

CodePudding user response:

You can define css variable which can be used almost anywhere1 in your css. To define a CSS variable, you need to use the -- prefix:

--my-variable: red;

You can, then, use this variable in your css, by using the function var

color: var(--my-variable);

You could use the setProperty function, on the style property of your element, to define the value for the variable you want

const color = 'red';

const input = document.getElementById('someInput');

input.style.setProperty('--my-variable', color);
<div  >
    <div style= "text-align: center;">
        <div id= "someInput" style= "background-color: var(--my-variable);">
            <img class= "fit";  id="img1" id="i" src="" style= ""/>
        </div>
    </div>
 </div>

1 Note, the scope of the css variable is determined by where it is declared in the hierarchy. In the previous exemple, since both the variable and the style that uses it are defined on the element directly, they are accessible. You could not use this variable on another element. See Css variable scoping for more information on the subject.

CodePudding user response:

there are many ways to use a variable from javascript in css, but one way that i think is the most efficient is by define a css variable, so you can reuse that css variable later on in the project.

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    var color = "red";
    
    //            
  • Related