bat
bat

Reputation: 31

jQuery text() change on toggle()?

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.

Upvotes: 3

Views: 15535

Answers (2)

Nick Craver
Nick Craver

Reputation: 630409

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"
    );
  });
});

Upvotes: 14

Ignacio
Ignacio

Reputation: 8035

You can use toggle on the form element.

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

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

Upvotes: 0

Related Questions