So Ville So Ville - 29 days ago 8
HTML Question

Button to make dynamic alert appear works only once then stops

I'm using Bootstrap, I have a collapsible div that appears at the press of a button, then disappears after 5 seconds.
The problem is, it only works once. When I press the button again, after the div has disappeared, nothing happens.
What could I do to make the button repeat the action once pressed again?
Here's my code:

<button type="button" class="btn btn-primary" data-dismiss="modal" data-toggle="collapse" data-target="#aparecer1">
Suscribir
</button>

<div id="aparecer1" class="alert alert-warning collapse">
This is an alert
</div>


$("button").click(function() {
setTimeout(function() {
$('#aparecer1').fadeOut('fast');
}, 5000);
});


Thanks a lot!

Answer

There are two reasons it doesn't work. Firstly the fadeOut() call results in display: none being set on the element inline, which overrides the style to show the element when applied on the next click. It needs to be removed. You also need to remove the in class on the element which gets added by Bootstrap. You can do both of these actions in the callback of fadeOut(), like this:

$("button").click(function() {
    setTimeout(function() {
        $('#aparecer1').fadeOut('fast', function() {
            $(this).css('display', '').removeClass('in');
        });
    }, 5000);
});

Example fiddle