To iterate individually on each element specified in *selector*
, use the each
operator, which is a function of JQuery [ .each () - for more details].
Within callback
use the setTimeout
of the javascript itself to manipulate a delay in the animation.
In the example below, some variables are used to aid in the orchestration of the effect ( var time
and var delay
).
Note that in the definition of the variable delay
it contains a if ternary ( MDN - Ternário Conditional Operator
) that validates the following condition: "If the container element ( #btn-menu
) of the <li>
elements is with the show class, will be 200 milliseconds between each <li>
, otherwise the delay will be 0 milliseconds (ie there will be no delay), hiding <li>
immediately.
In order for the if ternary to work, a toggleClass function has been inserted, which takes or places the show
class in 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><buttonid="btn-menu">MENU</button>
<ul id="menu">
<li>Menu1</li>
<li>Menu2</li>
<li>Menu3</li>
<li>Menu4</li>
</ul>