Search code examples
javascripthtmlmenudropdownnavbar

Getting dropdown menus to close when an item is selected


My webpage m1maths.com has a navbar with dropdown menus. I would like the menus to close when an item is selected, but they don't. A cut-down version of the navbar code is reproduced below. There is an html file with a bit of javascript which is meant to close the menus, followed by the css file.

I'm not good with javascript. The javascript in there is borrowed from the Internet. It is one of about 20 snippets from the Internet (including several from Stack Overflow) that I have tried without success. I have also tried writing my own and getting ChatGPT to write some. And I have asked three friends with some javascript knowledge to look at it. All without success. I am thinking that half a dozen lines of javascript should do the job if I can find the right code.

// function to close all dropdown menus
function closeAllDropdowns() {
  const allDropdowns = document.querySelectorAll(".dd ul");
  allDropdowns.forEach(function(dropdown) {
    dropdown.classList.remove("show");
  });
}


// close all dropdown menus when document is clicked
document.documentElement.addEventListener("click", closeAllDropdowns);
<table width="1000" border="0" align="center">
  <tbody>
    <tr>
      <td>

        <div class="navbar">
          <ul class="dd">

            <li>
              <div class="dd__item"><a href="#Modules"> Modules &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp </a></div>

              <ul class="dd ul">
                <li>
                  <div class="dd__item"> <a href="#A1">Algebra</a></div>
                  <ul>
                    <li><a href="#A4">Level 4 (about Year 10)</a>
                      <li><a href="#A5">Level&nbsp5&nbsp(about&nbspYear&nbsp10)</a>
                        <li><a href="#A6">Level 6 (Years 11-12)</a></li>
                  </ul>
                  </li>

                  <li><a href="#SMA">Arithmetic</a>
                  </li>
              </ul>
              </li>
          </ul>
        </div>

      </td>
    </tr>
  </tbody>
</table>


Solution

  • Please find updated code

    // function to close all dropdown menus
    function closeAllDropdowns() {    
        const allDropdowns = document.querySelectorAll(".dd ul");
        allDropdowns.forEach(function (dropdown) {
            // dropdown.classList.remove("show");
            dropdown.style.display = 'none';
        });
    }
    
    // function to open all dropdown menus
    function openAllDropdowns() {    
        const allDropdowns = document.querySelectorAll(".dd ul");
        allDropdowns.forEach(function (dropdown) {        
            dropdown.style.display = '';
        });
    }
    
    // close/open all dropdown menus when document is clicked
    document.documentElement.addEventListener("click", closeAllDropdowns);
    document.documentElement.addEventListener("mouseover", openAllDropdowns);
    

    Good Luck!!!