1

I'm just starting to teach myself Javascript and am trying to create a menu that is activated by clicking on a button. But I keep receiving the error: Uncaught TypeError: Cannot read property 'addEventListener' of null. I've been researching it for awhile, but can't figure out why it is not working. Please see my code below:

HTML

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="website.css" />
        <script src="sitejavascript.js"></script>
    </head>
    <body>
        <img class="himage" src="waves.jpg" style="width: 100%; height:150px;" />
        <div class="nav">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="SecondPage.html">Second Page</a></li>
                <li><a href="ThirdPage.html">Third Page</a></li>
                <li><a href="FourthPage.html">Fourth Page</a></li>
            </ul>
        </div>
        <div class="countrySelector">
            <button id="selectCountry" class="country">Testing</button>
            <div id="countryList" class="countryContent">
                <a href="#">Country One</a>
                <a href="#">Country Two</a>
                <a href="#">Country Three</a>
            </div>
        </div>
    </body>
</html>

Javascript

document.getElementById("selectCountry").addEventListener("click", dropCountry);
function dropCountry(){
    document.getElementById("countryList").classList.toggle("show");
};

The "show" is within my CSS

.show {display: block;}
Nathan
  • 13
  • 4

1 Answers1

2

Your script is running too soon, before the DOM is ready. Try putting your script tag at the bottom of the page, just before the closing body tag.

theMightyT
  • 92
  • 6