Javascript: multi level menu slide on button click

Tags: , , ,



Could you help me with this code?

$(document).ready(function(){
  /* Panel Slide */
  var btn = document.getElementsByClassName("btnBorder");
  var i;

  for (i = 0; i < btn.length; i++) {
    var panel = btn[i].nextSibling;
    btn[i].addEventListener("click", function() {
      $(".btnBorder").hide();
      panel.show();
    });
  }
});
<div id="menu" class="sector-row">
      <ul>
        <li>
          <div class="btnBorder flex">Logo <i class="ml-auto fa fa-angle-right"></i></div>
          <ul class="slide-panel">
              demo
          </ul>
        </li>
        <li>
          <div class="btnBorder flex">Navigazione <i class="ml-auto fa fa-angle-right"></i></div>
        </li>
        <li>
          <div class="btnBorder flex">Widgets <i class="ml-auto fa fa-angle-right"></i></div>
        </li>
        <li>
          <div class="btnBorder flex">Footer <i class="ml-auto fa fa-angle-right"></i></div>
        </li>
      </ul>
    </div>

I would like to make a menu slide with multi level but the element “slide-panel” is not showing up…

Answer

I’m not a big fan of mixing pure javascript with jquery .. so the next code is in jquery .. Also I prefer to use add/remove/toggleClass instead of hide/show()

$(document).ready(function(){
  $('.btnBorder').on('click' , function(e){
    var ul_selector = $(this).next('ul.slide-panel'); // OR $(this).closest('li').find('ul.slide-panel');
    e.stopPropagation(); // it will prevent the parent click if you've one
    $('ul.slide-panel').not(ul_selector).addClass('hide'); // if you need to hide other slide-panels 
    ul_selector.toggleClass('hide'); // toggle the class hide which in css is display:none and added to the slide-panel html element
  });
});
.slide-panel.hide{
  display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="menu" class="sector-row">
  <ul>
    <li>
      <div class="btnBorder flex">Logo <i class="ml-auto fa fa-angle-right"></i></div>
      <ul class="slide-panel hide">
        Demo
      </ul>
    </li>
    <li>
      <div class="btnBorder flex">Navigazione <i class="ml-auto fa fa-angle-right"></i></div>
    </li>
    <li>
      <div class="btnBorder flex">Widgets <i class="ml-auto fa fa-angle-right"></i></div>
    </li>
    <li>
      <div class="btnBorder flex">Footer <i class="ml-auto fa fa-angle-right"></i></div>
    </li>
  </ul>
</div>

Note: The problem when using .next() if the element has <!-- --> or </br> it will not select the correct element .. So you can use .closest().find() you’ll find it in my code above



Source: stackoverflow