skip to Main Content
<head>
  <script>
    var bgcolor = #ff0000
  </script>
</head>
<body style="background-color: var(--bgcolor);">
</body>

I want to make a JS function which would change the background color on certain input. I’m playing around with JS functions, and I can’t get the "var" to work in the HTML file. Can somebody check my code for correctness?

4

Answers


  1. Though variables are same in name and use, the way they are implemented are different between CSS and Javascript. They are not interchangeable. You’ll want to set it up similar to this:

    <head>
      <style>
        :root {
          --bgcolor: #ff0000
        }
      </style>
    </head>
    <body style="background-color: var(--bgcolor);">
    </body>
    Login or Signup to reply.
  2. Short answer ? No. CSS variables are different from JS variables

    FYK: A good alternative would be to use a DOM method, it is explained here, although I do not think it will really be useful in this case (will definitely be useful later tho): https://www.w3schools.com/Css/css3_variables_javascript.asp

    PS: I assume you’re beginning with js, but I’d recommend using let or const to declare variables, I’ll let you do some research about that.

    Login or Signup to reply.
  3. This will not work because HTML is a markup language and is a static page by default. It does not have the ability to render dynamic properties by itself. This is where JS is beneficial because it can manipulate the DOM.

    To get something like this to work you would need to add some Element in your HTML Markup that you can add a listener to in your JS script and then run some code when it is triggered.

    A button will work for this example but keep in mind there are MANY forms of elements to choose from to add listeners to and specific types of triggers.

    You can read this to for more info:
    https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>The Document Object</h1>
    <h2>The body Property</h2>
    
    <p>Change the background color of this document.</p>
    
    <button id="submit">Submit</button>
    
    <script>
    const button = document.getElementById("submit")
    
    const changeBackgroundColor = () => {
        document.body.style.backgroundColor = "#ff0000";
    }
    
    button.addEventListener("click", changeBackgroundColor)
    
    </script>
    
    </body>
    </html>
    Login or Signup to reply.
  4. you can insert this variable using template literal like this

    <head>
      <script>
        var bgcolor = #ff0000
      </script>
    </head>
    <body style=`background-color: ${bgcolor} ;`>
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search