Reputation: 3
I want to create a div and remove it after 5 seconds, the problem i have is that myscript is removing all the divs at the same time, and I want you to remove the divs in order of creation, one by one.
Here my script until now:
$(document).ready(function(){
$(".create").click(function(){
//HERE I CREATE THE DIVS
$('.divs').append('<div class="deleteon5seconds">Hello</div>');
//HERE FINISH CREATE THE DIVS
});
});
//HERE I DELETE THE DIVS IF IT EXIST
var $auto_refresh = setInterval(function () {
var $articleCount = $('.deleteon5seconds').length;
while ($articleCount > 0) {
$('.deleteon5seconds:last-child').remove();
$articleCount = $('.deleteon5seconds').length;
}
$autoUpdate();
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div>
All this is an example, the purpose of the code is to show alerts. I need help please! Advanced thanks!!
Upvotes: 0
Views: 40
Reputation: 45155
So if I understand what you are asking, for each div created, you will need to get a reference to that new div and then use setTimeout
(not setInterval
) for each one with an interval of 5 seconds that will remove that particular div. This make it so each new div will live for 5 seconds and then disappear.
var count = 1;
$(document).ready(function(){
$(".create").click(function(){
//HERE I CREATE THE DIVS
var div = $('.divs').append('<div class="deleteon5seconds">Hello' + count++ + '</div>');
var elem = $('.divs div.deleteon5seconds').last();
//HERE FINISH CREATE THE DIVS
setTimeout(() => elem.remove(), 5000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div>
I added the count
part just to make it easier to keep track of which div is which.
Upvotes: 1
Reputation: 485
You can delete the first created element of that class with $('div.deleteon5seconds').first().remove();
.first()
Description: Reduce the set of matched elements to the first in the set.
The problem here is that you have added while and it deletes them all. Check my fiddle
$(document).ready(function(){
$(".create").click(function(){
//HERE I CREATE THE DIVS
$('.divs').append('<div class="deleteon5seconds">Hello</div>');
//HERE FINISH CREATE THE DIVS
});
});
//HERE I DELETE THE DIVS IF IT EXIST
var auto_refresh = setInterval(function () {
var articleCount = $('.deleteon5seconds').length;
if (articleCount > 0) {
$('div.deleteon5seconds:first-of-type').remove();
articleCount = $('.deleteon5seconds').length;
}
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div>
Upvotes: 0