3

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.

2 Answers 2

14

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"
    );
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

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 - 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?
0

You can use toggle on the form element.

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

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

1 Comment

the mentioned syntax is for toggle, not for slidetoggle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.