简体   繁体   中英

toggle child of clicked class pure Javascript - no JQuery

I have two toggles with a class .submenu-toggle and they contain a ul child with a class .submenu. What I would like to happen is when the user clicks on .submenu-toggle the ul child(.submenu) of that class(submenu-toggle) is shown and then when it is clicked again it is hidden.

I need to achieve this using pure Javascript without any JQuery.

If you're able to also let me know how to hide .submenu if the user clicks outside that element... that would be awesome!

Thanks for your time and help.

Here is my current Javascript:

      // Drop Down Menus
      var subToggle = document.getElementsByClassName("submenu-toggle");
      var menu = subToggle.children;

      for (var i = 0; i < subToggle.length; i++) {
          subToggle.item(i).onclick = function () {

              menu[1].style.display = "block";
          }
      }

Here is my current html:

<ul>
     <li class="submenu-toggle"><a href="#">Menu 1</a>
        <ul class="submenu">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li class="submenu-toggle"><a href="#">Menu 2</a>
        <ul class="submenu">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
</ul>

You could easily do this menu with CSS. But here's an example with vanilla JavaScript:

// JS
var submenu = document.getElementsByClassName("submenu-toggle");

for (var i = 0; i < submenu.length; i++) {
    submenu[i].addEventListener('click', menus, false);
}

function menus() {
  var menu = this.querySelector('.submenu');
  menu.classList.toggle("hidden");
};

// CSS

.hidden {
   display: none;
}

DEMO - Codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM