Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

jquery - Javascript: multi level menu slide on button click

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>
question from:https://stackoverflow.com/questions/65877460/javascript-multi-level-menu-slide-on-button-click

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...