Display one item at a time with jQuery

Asked

Viewed 130 times

3

I created a menu to see the possibilities with the jQuery animations. I wanted, when I clicked the button, jQuery to display each LI at a time, 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>

2 answers

6


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

And the aspect of the effect you get playing with the values of the delay and the interval of the animation.

$(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>

  • But what did you do in the code that now has animation left to right and top to bottom? !!

  • @Wallacecorrêa this is conquencia do toggle(), had not seen that you were using the `slideToggle(), see the edition.

  • @Wallacecorrêa was the aspect you wanted?

  • yes! Thank you very much :D

2

To iterate individually on each element specified in *selector*,the operator shall be used each, which is a Jquery function [ .each() - for more details].

Within the callback use the setTimeout own javascript to manipulate a delay in the animation.

In the example below some variables are used to assist in the orchestration of the effect (var time and var delay).

Note that in the variable definition delay contains a if ternary (MDN - Ternary Conditional Operator ) validates the following condition: "If the element container (#btn-menu) of the elements <li> be with class show, the display delay will be 200 milliseconds between each <li>, otherwise the delay will be 0 milliseconds (ie there will be no delay), hiding the <li>immediately.

So that the if ternario function toggleClass, which removes or places the class showin the container.

$(document).ready(function(){
    $("#btn-menu").click(function (){
        // Inserindo ou removendo a class do container
        $(this).toggleClass('show');
        
        // Variáveis que auxiliam a orquestrar a animação
        // =============================================
        var time = 0;
        // If ternário que define a quantidade de milissegundos
        var delay = $("#btn-menu").hasClass('show') ? 300 : 0;
        //===============================================
        // Operador EACH do jquery ( Muito semelhante ao convencional Foreach)
        // @Parâmetro 1 - indice atual da iteração
        // @Parâmetro 2 - elemento atual da iteração
        $("li").each(function(index, el){
          time = time + delay; // para cada elemento é incrimentado mais milissegundos na variável time
          
          // Temporizador nativo do JS
          // Parâmetro 1 - callback
          // Parâmetro 2 - tempo em milissegundos
          setTimeout(function(){
            // ternario que faz o SlideDown ou Fadeout
            $("#btn-menu").hasClass('show') ? $(el).slideDown('show') : $(el).fadeOut('slow');
          }, time);
        });
    });
});

/** restante do código **/
li{
    background-color:red;
    border-bottom: 1px solid white;
    width: 50%;
    display: none;
}
<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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.