I want to hide my bootstrap alert if it is empty. It hide correctly when page load, problem is when I do a push who insert data into div, it don´t show alert and it keep with display = none
HTML
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
JS:
<script type="text/javascript">
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + '#discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
</script>
Edit
I try it using input event
, it occurs same. It hide but it don't show when get value
JS:
<script type="text/javascript">
$('#discussion').keyup(function () {
// If value is not empty
if ($(this).val().length == 0) {
// Hide the element
$('#a1').hide();
} else {
// Otherwise show it
$('#a1').show();
}
}).keyup();
</script>
Your selector must be #a1 #discussion
no #a1#discussion
.So:
Change :
$('#' + id + '#discussion')
To:
$('#' + id + ' #discussion')
^-----------------
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
After Update your question:
setInterval(function(){ hideAlert("a1"); }, 3000);
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion" contenteditable="true">Some Text...</div>
</div>
Note : Remove text in div
and see result
Why not try using the :empty css pseudo-class like this:
#discussion{
display: block;
}
#discussion:empty{
display: none;
}
<div id="discussion" class="alert alert-success"></div>
Note: The beginning and closing tags should be next to each other for the pseudo-class to work (like the beginning and closing div tags next to each other without any line breaks or space in the html shown above).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With