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 show
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>
<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? !!
– Wallace Corrêa
@Wallacecorrêa this is conquencia do
toggle()
, had not seen that you were using the `slideToggle(), see the edition.– Leandro Angelo
@Wallacecorrêa was the aspect you wanted?
– Leandro Angelo
yes! Thank you very much :D
– Wallace Corrêa