1

I have a question when writing js. I define a toys variable in the beginning of the file, it works when I do it in console in chrome, but within the js file, i got an error when trying to use it, it says toys is null. index.js file:

let addToy = false

let toys = document.getElementById("toy-collection")

document.addEventListener("DOMContentLoaded", ()=>{
  const addBtn = document.querySelector('#new-toy-btn')
  const toyForm = document.querySelector('.container')
  addBtn.addEventListener('click', () => {
    // hide & seek with the form
    addToy = !addToy
    if (addToy) {
      toyForm.style.display = 'block'
    } else {
      toyForm.style.display = 'none'
    }
  })

  fetchToys()
})


function fetchToys(){
  fetch("http://localhost:3000/toys")
  .then(resp=>resp.json())
  .then(json=>addJsonToBlock(json))
}


function addJsonToBlock(json){
  for (const toy of json){
    toys.innerHTML += `<div class='card'>${toy.name}</div>`
  }
}

index.html file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>Toy Tale</title>
    <script type="text/javascript" src="src/index.js"></script>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div id="toy-header">
      <img
        src="https://fontmeme.com/permalink/180719/67429e6afec53d21d64643101c43f029.png"
        alt="toy-header"
      />
    </div>

    <div class="container">
      <form class="add-toy-form">
        <h3>Create a toy!</h3>

        <input
          type="text"
          name="name"
          value=""
          placeholder="Enter a toy's name..."
          class="input-text"
        />
        <br />
        <input
          type="text"
          name="image"
          value=""
          placeholder="Enter a toy's image URL..."
          class="input-text"
        />
        <br />
        <input
          type="submit"
          name="submit"
          value="Create New Toy"
          class="submit"
        />
      </form>
    </div>
    <p style="text-align:center">
      Andy needs your help! <button id="new-toy-btn">Add a new toy!</button>
    </p>

    <div id="toy-collection"></div>
  </body>
</html>

Yingqi
  • 297
  • 4
  • 12

1 Answers1

1

Move your script to the bottom of body before the closing </body> tag.

<script type="text/javascript" src="src/index.js"></script>

It's not working because it's loaded before the DOM has loaded. When you include it at the end, then it loads after the DOM has loaded.

Joshua Obritsch
  • 1,081
  • 4
  • 10