1

I'm trying to make a string in JavaScript that can be changed through a button later on. I want this string to contain colors for my index.html to use to change the background. How do I call the variable from JavaScript into HTML while still keeping the ability to change the variable at anytime and having the webpage update to display the changes. (sorry if this is confusing)

example:

script.js

var color = "";

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Type</title>
  </head>
  <body style="background-color:"color";">



    <h1><center>Type</center></h1>
    <p><center>This is a test sentence</center></p>

  </body>
  <script src="script.js"></script>
</html>
Gavin C.
  • 105
  • 8

2 Answers2

1

You could try something like this:

/* This is script.js */

var color = "black";
body {
  color: white;
}
<!DOCTYPE html>
<html>
<head>
  <title>Type</title>
</head>
<body onload="document.body.style.backgroundColor = color;">
  <h1>
    <center>Type</center>
  </h1>
  <p>
    <center>This is a test sentence</center>
  </p>
</body>
<script src="script.js"></script>
</html>

This sets the color inline, which is (sort of?) what I believe you wanted, except you just use the onload attribute instead of using the style attribute.

Spectric
  • 30,714
  • 6
  • 20
  • 43
0

You want to bind the background-color CSS property to the JavaScript color variable, but there's no direct way to do that. Instead of updating a JavaScript variable, just update the background-color of the body element.

document.querySelector('body').style.backgroundColor = 'red';

There are a lot of JavaScript frameworks that support binding JavaScript data to DOM elements, but at the end of the day, they're all just copying values from JavaScript into the DOM, the same as we're doing here.

If you really want to have a JavaScript variable, you can have it, then call some function like updateBackgroundColor, that copies the color from the variable into the DOM.

Willis Blackburn
  • 8,068
  • 19
  • 36
  • How would I implement this? I'm very new to "vanilla" JavaScript and HTML. I've no clue how to implement this into my current program. – Gavin C. Feb 21 '21 at 00:40