0

I am making a menu and I am currently implementing a feature where you can close the menu. I have three different menus inside of an overlay. When you close the menu I want the overlay to be display: none;. I have three buttons that do this (one for each menu). However, only the button at the top of the HTML code works. I know it is only the one at the top, because I tried deleting the one that was on the top, and then the second button would work since that is now the top button. I also tried giving different IDs, but that didn't make a difference.

Here is a shortened version of the parts of my code that I am talking about:

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

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

closeMenu.addEventListener('click', function() {
  overlay.style = "display: none;";
});
<div class="overlay" id="overlay">
      <div class="selectMenu" id="selectMenu">
        <div class="h2Wrapper">
          <h2>Create Canvas</h2>
          <button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
        </div>
      </div>
      <div class="selectMenu2" id="selectMenu2">
        <div class="h2Wrapper">
          <h2>Upload Image</h2>
          <button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
        </div>
      </div>
      <div class="selectMenu3" id="selectMenu3">
        <div class="h2Wrapper">
          <h2>Create Blank</h2>
          <button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
        </div>
      </div>
    </div>
Emil
  • 107
  • 2
  • 12

1 Answers1

2

First of all, the attribute id must be unique in a document, use class instead. Then you can target all the element with the class to loop through them and attach the event individually:

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

var closeMenu = document.querySelectorAll(".closeMenu");

closeMenu.forEach(function(cm){
  cm.addEventListener('click', function() {
    overlay.style = "display: none;";
  });
});
<div class="overlay" id="overlay">
  <div class="selectMenu" id="selectMenu">
    <div class="h2Wrapper">
      <h2>Create Canvas</h2>
      <button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
    </div>
  </div>
  <div class="selectMenu2" id="selectMenu2">
    <div class="h2Wrapper">
      <h2>Upload Image</h2>
      <button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
    </div>
  </div>
  <div class="selectMenu3" id="selectMenu3">
    <div class="h2Wrapper">
      <h2>Create Blank</h2>
      <button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
    </div>
  </div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59