Since the other answers were a bit lacking I decided to give you a complete answer.
First, you should look at how you're trying to get the elements since it's the most obvious one.
When trying to get an element by its tag name, you need to use document.getElementsByTagName
, however like the name implies you will get several results instead of one, and the result will be a HTMLCollection
However, the simplest way would be to add an id to your heading.
<h1 id="heading">Change the background color!</h1>
What about body? No need to use id's you can access body with:
const body = document.body
Next it's really recommended to load your script after the page has done loading, so place your script file at the end of the body tag, like so:
<body>
...
<script src="./script.js"></script>
</body>
You could use defer, read up on it here Where should I put <script> tags in HTML markup?
Next, let's look at your javascript
The first rule of javascript, unless you know what you're doing, never use var, use let
or const
instead.
const
for constants
let
for variables that will have a value re-assigned
Instead of using var
to you save the colors, you can use let, since you will be re-assigning them later like so:
let backgroundColor = null
let headingColor = null
Notice, I'm also renaming your variables
As for the elements, you don't need to get their dom reference every time, instead, save them in a constant since you don't want them to change.
const body = document.body
const colorInput = document.getElementById('color')
const h1 = document.getElementById('heading')
Notice how we're using document.getElementById()
and document.body
Last but not least, all you need to do now is assign the color variables with the current value of the colorInput
And then apply it to the style of the referenced elements in saveColors()
function changeBackgroundColor() {
backgroundColor = colorInput.value
}
function changeHeaderColor() {
headingColor = colorInput.value
}
function saveColors() {
body.style.backgroundColor = backgroundColor
h1.style.backgroundColor = headingColor
}
Code
index.html
<!DOCTYPE html>
<html>
<head>
<title>Change the background color!</title>
</head>
<body>
<h1 id="heading">Change the background color!</h1>
<input type="color" id="color" value="#1784b3" /><br />
<button onclick="changeBackgroundColor();">Save background color</button>
<button onclick="changeHeaderColor();">Save header color</button>
<button onclick="saveColors();">Apply changes to page</button>
<script src="./script.js"></script>
</body>
</html>
script.js
const body = document.body
const colorInput = document.getElementById('color')
const h1 = document.getElementById('heading')
let backgroundColor = null
let headingColor = null
function changeBackgroundColor() {
backgroundColor = colorInput.value
}
function changeHeaderColor() {
headingColor = colorInput.value
}
function saveColors() {
body.style.backgroundColor = backgroundColor
h1.style.backgroundColor = headingColor
}