views:

73

answers:

3

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.

+4  A: 

$("#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.

Jonathan Sampson
+3  A: 

I think you want to use toggle().

Upper Stage
Specifically `fadeToggle()`.
Joel Potter
Thanks. toggle probably is better. Although how can I make the effect fade? I don't see any parameters that toggle accepts to chose what effect you want?
Matt
~Joel, fadeToggle() doesn't seem to be a jQuery function?
Matt
Matt, it's a custom plugin.
Jonathan Sampson
+3  A: 

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() 
 }); 
Paul Creasey
Awesome, cheers.
Matt
Matt, you should change your question. The selected answer doesn't address the question you posed.
Jonathan Sampson
+1, but you should have also given an example using speed, easing, and the optional callback (or set defaults within the function);
cballou