Search code examples
javascriptevent-handling

How to use JavaScript Event Handler to make an image dissapear when clicking on it


I'm learning JavaScript and I want to make a section of my code change to display: none when clicking on an image that is inside the section of code. I'm trying to add an event handler but it doesn't seem to be working, even though examples I've followed have the same structure.

This is my js file.

let banner = document.getElementById("banner");
let screen1 = document.getElementById("screen1");

function changeDisplay() {
    screen1.style.display = "none"
}

banner.addEventListener("click", changeDisplay);
<body>
    <script src="interactive.js"></script>

    <!-- Header -->
    <div id="screen1" class="header section">

      <!-- Title -->
      <div id="title">
        <img src="https://picsum.photos/id/1/20/30">
        <h1>The Legend of Zelda: Almanac</h1>
        <img src="https://picsum.photos/id/1/20/30">
      </div>

      <!-- Subtitle -->
      <h3>A Complete Collection of all TLoZ Games</h3>

      <!-- Main Image -->
      <img id="banner" src="https://picsum.photos/id/1/20/30">
    </div>
</body>


Solution

  • The script tag should be at the bottom of your code, since the document has not finished parsing by the time the "getElementById" in the script executes.

    An alternative is to include the attribute "defer" when referencing the script, which will delay the execution until the document is parsed.

    Another option would be to use what you are learning with document and "DOMContentLoaded", to make sure you code is executed after the page is loaded. Your js code, therefore, would look like this:

    function afterLoadPage() {
        let banner = document.getElementById("banner");
        banner.addEventListener("click", changeDisplay);
    }
    
    function changeDisplay() {
        let screen1 = document.getElementById("screen1");
        screen1.style.display = "none"
    }
    
    document.addEventListener("DOMContentLoaded", afterLoadPage);