views:

43

answers:

2

Hello.

I want to make a script that is changing toggle link text depending on others element visibility.

So while #form is visible I want the #form-container a text to be "Hide...", and while it's hidden I want the text to be "Show...".

I've tried this line - if($('#form').is(":visible")){ another way: if($('#form').is(":visible") == "true"){ - but it also doesn't work.

What's wrong? How to change text every time another item is toggled?

$('.toggle').click(
    function()
    {
        $('#form').slideToggle();

            if($('#form').is(":visible")){
                $('#form-container a').text("Hide form container");
            }
            else {
                $('#form-container a').text("Show form container");  
            } 
    });

Thanks.

A: 

You can use toggle on the form element.

$("#form").slideToggle(
  function () {
    //Hide
  },
  function () {
    //Show
  }
);

source: http://api.jquery.com/toggle/

ign
Thanks, didn't work for me, but used the first solution.
bat
+1  A: 

It'll always be visible while animating, you can check the visibility in the .slideToggle() callback so it checks when it finishes animating, like this:

$('.toggle').click(function() {
  $('#form').slideToggle(function() {
    $('#form-container a').text(
      $(this).is(':visible') ? "Hide form container" : "Show form container"
    );
  });
});
Nick Craver
Thanks, it works. But why it always be visible WHILE animating? I look at my code and it should be already shown/hidden before if statement?
bat
@bat - You're calling the `.slideToggle()` before the check, so when it's showing it *just* started being shown, it's barely visible, but it is `:visible`. When you're closing it, it takes time to animate (400ms), so it's still closing when the check runs...in either case, it's `:visible`, make sense?
Nick Craver