Checking if a DIV is currently shown on the page
-
19-09-2019 - |
Question
I'm learning jQuery and this is my code so far:
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$('#login-box').fadeIn('fast');
});
});
</script>
It works, when you click the login button the DIV called login-box
shows on the page. What I wanted to do was if the login button was clicked again, the login-box
DIV will fade from the page. What would be the best way to do this? I was thinking:
$(document).ready(function(){
$('#login').click(function(){
if(login-box-is-showing)
{
$('#login-box').fadeOut('fast');
} else {
$('#login-box').fadeIn('fast');
}
});
});
But I'm confused at how I would determine if the DIV is showing or not. I also see that jQuery has a toggle function, would that be better?
Thanks.
Solution
from Karl Swedberg
jQuery.fn.fadeToggle = function(speed, easing, callback) {
return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
Then, you can do this:
$("#login").click(function () {
$("#login-box").fadeToggle()
});
OTHER TIPS
$("#login-box:visible")
will tell you if it's visible, while $("#login-box:hidden")
tells you if it's not. However, an easier way of handling this would be to use $.toggle()
or even $.slideToggle()
if you want a bit of an added effect.
I think you want to use toggle().