Reputation: 9293
Need to slideUp
elements sequencially, one by one, not asynch.
block2
should start sliding when block1
is closed.
block3
should start sliding when block2
is closed.
And so on. In reality I have a lot of such elements so any nested syntax (function inside function) is not suitable.
I hope async await
is the right way but cannot understand fully.
Here is my try:
$('button').on('click', function(){
close_all();
});
async function close_all(){
await close1();
await close2();
await close3();
}
function close1(){
$('#block1').slideUp();
}
function close2(){
$('#block2').slideUp();
}
function close3(){
$('#block3').slideUp();
}
.block{
display:inline-block;
width:14%;
background:gold;
margin:0 9px;
}
#block1{
height:54px;
}
#block2{
height:25px;
}
#block3{
height:72px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='block' id='block1'>BLOCK 1</div>
<div class='block' id='block2'>BLOCK 2</div>
<div class='block' id='block3'>BLOCK 3</div>
<button>CLICK</button>
Upvotes: 2
Views: 94
Reputation: 17190
One way could be using the on complete
callback that you can use on the slideUp() method:
$('button').on('click', function()
{
close_all($(".block"));
});
function close_all(elements, idx=0)
{
if (idx >= elements.length)
return;
let cb = () => close_all(elements, idx + 1);
elements.eq(idx).slideUp(2000, cb);
}
.block {
float: left;
width:14%;
background:gold;
margin:0 9px;
}
#block1{
height:54px;
}
#block2{
height:25px;
}
#block3{
height:72px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='block' id='block1'>BLOCK 1</div>
<div class='block' id='block2'>BLOCK 2</div>
<div class='block' id='block3'>BLOCK 3</div>
<button>CLICK</button>
Upvotes: 1