0

I wanted to add an event listener to a second button that changes the font size of the heading when you click it, but when I execute the code, the web console returns "button2 is null." How can I make this code work? I don't know what is wrong with my button2 code.

const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById("myTextInput")
const FontSize = document.getElementById("myFontSize");
const button2 = document.getElementById("button2");

myButton.addEventListener("click", () => {
    myHeading.style.color = myTextInput.value;
});

button2.addEventListener("click", () => {
    myHeading.style.fontSize = FontSize.value;
});

html code:

!DOCTYPE html>
<html>
    <head>
        <meta charset = "UTF-8">
        <title> Javascript </title>
    </head>

    <body>
    <h1 id="myHeading"> Javascript </h1>
    <p> making a web page interactive </p>
    <input type="text" id="myTextInput">
    <button id="myButton"> Change headline color </button>
    <script src="dom.js"> </script>
    <input type="text" id="myFontSize">
    <button id="button2"> Change Font Size </button>
</body>
</html>
Shirley
  • 29
  • 1
  • 7
  • Show the HTML code. But i bet it's because while the script is executed, a button with id `button2` don't exists. Make sure your script is loaded after `DomContentLoaded`. – cyr_x Jun 14 '17 at 22:04
  • thanks it was bc the script was loaded before. – Shirley Jun 14 '17 at 22:11

1 Answers1

0

Figured it out! It was because the script code was before the button2 code. Thanks!

Shirley
  • 29
  • 1
  • 7