I have an empty div I use for status messages once my jQuery script executed successfully. I have various jQuery / AJAX calls that use the same div for status messages, however after the first script and first successful population of the div, the div is not reusable anymore, meaning the success message of the second script is not displayed.
How can I populate and then clear a div content in order for it to remain re-useable later?
// populate status div
$('#status').html(response);
// remove success message after 5 secs
setTimeout(function() {
$('#status').fadeOut('fast');
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="status"></div>
I tried various other jQuery ways to clear the content, but all have the same result.
$('#status').empty()$('#status').val('')$('#status').end()Please read documentation on what these jQuery methods does.
.empty() - removes all child elements
.val('') - is intended to be used on input elements only
.end() - End the most recent filtering operation in the current chain and return the set of matched elements to its previous state - does nothing to content itself.
You do not need to clear any content, since fadeOut will hide element. What you want to do is fadeIn that element again and set new content to it
// populate status div
setContent('Initial content');
// remove success message after 5 secs
setTimeout(function() {
$('#status').fadeOut('fast');
}, 5000);
// show success message again after 10 secs
setTimeout(function() {
setContent('Repeated content');
}, 10000);
function setContent(content) {
$('#status')
.html(content)
.fadeIn('fast');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="status"></div>