You can use this:
$('#message:visible').delay(2000).hide('fade');
문제
I have an element <p id="message" class="hidden">...</p>
My CSS:
.hidden{
display:none;
}
.show{
display:block;
}
Question : I need help to in JQUERY to check whether the element is hidden or shown. If its shown, hide it(possibly fadeout) after 2 seconds. I need help in checking the element's class whether its active or not. I have no idea how to proceed
Current JQuery:
$(function() {
setTimeout(function() {
$("#message").hide('blind', {}, 500)
}, 2000);
});
해결책
다른 팁
You can check if an element is visible using the following
$(element).is(":visible")
Taken from https://api.jquery.com/visible-selector/
Elements with visibility: hidden
or opacity: 0
are considered visible, since they still consume space in the layout.
You could do something like the following
if($("#message").is(":visible"))
{
$("#message").delay(2000).fadeOut();
}
Use .hasClass()
to check if it has .hidden or .show
You can also use
$(".hidden").css("display")
or
$("#message").css("display")
in an if/else statement to check wether the object is already visible or not
see css method - jquery API
Two ways:
if ($('p').hasClass('hidden') == true) {
//Script if it's hidden
}
else {
//Script if it's visible
}
Or
if ($('p').css('display') == 'block') {
//Script if it's visible
}
else {
//Script if it's hidden
}
If you want to check if an element has a class is as simple as $(selector).hasClass('yourClass');
Ive adjusted your code with a setInterval
so you clearly see how hasClass works.
var $message = $('#message');
setInterval(function() {
if($message.hasClass('show')) {
$message.removeClass('show');
$message.fadeOut('slow',function() {
$message.addClass('hide');
});
} else {
$message.removeClass('hide');
$message.fadeIn('slow',function() {
$message.addClass('show');
});
}
}, 2000);
You can check visibility like this
$(document).ready(function(){
if ($('#myDiv').is(":visible"))
{
//visible do some than
}
else
{
//not visible do some else
}
});