I am trying to create div's on demand which then timeout and are then hidden and removed from the dom. The display property of "load_bar" is set to none so that I can use the last selector to get a reference to the instance I have just created. It is important that this solution can create several div's which are running on their own timeout clock
$(document).ready(function () {
$('#add').click(function () {
var t = Math.random()*20;
alert(t);
var destination = $('input').val();
$('#holding_pen').append('<div class="load_bar">'+destination+'</div>');
$('.load_bar:last').show().delay(t).hide().remove();
});
});
Every thing works to create divs when I remove .delay().hide().remove();
However when I add this the div is not shown at all
Create proper elements, that way you'll have a reference to the element within the function:
$(document).ready(function () {
$('#add').click(function () {
var t = (Math.random()*20)*1000,
destination = $('input').val(),
div = $('<div />', {'class':'load_bar', text: destination});
$('#holding_pen').append(div);
div.show(1).delay(t).hide(1, function() {
$(this).remove();
});
});
});
Also, hide()
and show()
does not work with the animation queue and subsequently not with delay()
unless a duration is given, and that's why the element is never shown, delay()
doesn't work and the element is hidden right away.
EDIT:
Also, remove()
is not an animated method, so it doesn't work with delay()
, but hide()
a useful callback for that, see edited code above.