0

I am attempting to create a basic single page application (without any frameworks), which will give users tutorials on certain subjects.

I am getting an error with the javascript for the page as follows:

Uncaught TypeError: Cannot read property 'addEventListener' of null

Here is the javascript I use to load in the json data:

var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
  var TutRequest = new XMLHttpRequest();
  TutRequest.open('GET', 'https://api.myjson.com/bins/iyvun');
  TutRequest.onLoad = function(){
    var TutData = JSON.parse(TutRequest.responseText);
    console.log(TutData[2]);
   };
 TutRequest.send();
})

This is my HTML code :

<html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="javaScript.js"></script>
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>


        </nav>
    </header>

</body> 

The output of the code should be the json data from the URL provided in the JS code but I seem to only get this error with anything I'm trying. Any help with this is appreciated.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

1

That happen because the DOM isn't fully loaded when the script run, put you JS include at the end of the body tag when the elements that you want to attach the event to are ready and loaded like :

<html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>


        </nav>
    </header>

    <script src="javaScript.js"></script>
</body> 
</html>
halfer
  • 19,824
  • 17
  • 99
  • 186
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101