javascript – Display one item at a time with jQuery

Question:

I created a menu to see the possibilities with jQuery animations. I wanted when I clicked the button, jQuery would display each LI in turn, not all at the same time.

I wanted a different delay in each LI . How do I do?

The code I have is this:

$(document).ready(function(){
    $('li').hide();

    $("#btn-menu").click(function (){
        $("li").slideToggle(600);
    });
});

$('li').hover(function(){
    $(this).css({
        'background-color':'#000000',
        'color': 'white'
    });

},function(){
    $(this).css({
        'background-color': 'red',
        'color': 'black'
    });
}
);
li{
    background-color:red;
    border-bottom: 1px solid white;
    width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn-menu">MENU</button>

<ul id="menu">
    <li>Menu1</li>
    <li>Menu2</li>
    <li>Menu3</li>
    <li>Menu4</li>
</ul>

Answer:

You can use a foreach with a delay() , multiplying by the "index"… so I believe you will get the desired effect.

And the effect aspect you get by playing with the animation's delay and interval values.

$(document).ready(function() {
      
      $("#btn-menu").click(function() {
        var lista = $("#menu li").css('display') === 'none' ?
          $("#menu li") :
          $($("#menu li").get().reverse());

        lista.each(function(i) {
          $(this).delay(200 * i).slideToggle(100);
        });
      });
});
li {
  background-color: red;
  border-bottom: 1px solid white;
  width: 50%;
  color: black;
  display: none;
}

li:hover {
  background-color: #000000;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn-menu">MENU</button>

<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>
Scroll to Top