Event listener not listening Javascript

So my code isn’t really work when I press the button. Please help.
Code:`

* { margin: 0; padding: 0; box-sizing: border-box; }
body {
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #586bcc;
}
.text {
  padding-bottom: 50px;
  line-height: 62.5px;
  font-size: 25px;
}
.hi {
  text-align: center;
}
.button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 24px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #cad642;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: #3e8e41;
}

.button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
h1,
h3 {
  text-align: center;
  font-family: "Roboto";
}

Welcome to my Unit 4 Concept Review Game.

Here you will be put through 10 painful(not really but you know) questions.

Can you face the science gauntlet?

Click Me
`

your code is not showing up right in the post

Here’s the link to the project:

Ah thanks. Here’s the code, reposted (CSS omitted):

  <script>
    document.getElementById("start").addEventListener("click", myFunction);

    function myFunction() {
      alert("works")
    }
  </script>
  <html>
    <div class="text">
      <h1>
        Welcome to my Unit 4 Concept Review Game.
      </h1>
      <h3>
        Here you will be put through 10 painful(not really but you know)
        questions.
      </h3>
      <h1>
        Can you face the science gauntlet?
      </h1>
    </div>
    <div class="hi">
      <button class="button" id="start">Click Me</button>
    </div>
  </html>

Up there in the script, at that point in the parsing steps, the browser hasn’t yet created the ‘start’ button, so the later addEventListener would fail. You could resolve that by moving the script to after the button in the markup.

2 Likes

Thanks a lot!

1 Like