Adam
Adam

Reputation: 29079

Change text if div is visible

The following jsFiddle changes text of #more depending on the visibility of #extra:

<style>
#extra{
  display: none;
}
</style>

<a href="#" id="more">More about us</a>
<div id="extra">Some Text</div>

<script>
$('#more').click(function() {        
    if ($('#extra').is(':visible')) {
        $(this).text('Less about us');
    } else {
        $(this).text('More about us');
    }

    $('#extra').slideToggle('fast');   
});
</script>

This works fine. However, it does not work anymore if I put the slideToggle() above the if-statement like this (see this jsFiddle):

$('#more').click(function() {
    $('#extra').slideToggle('fast');

    if ($('#extra').is(':visible')) {
        $(this).text('More about us');         
    } else {         
        $(this).text('Less about us');
    }
});

In this example, the text will remain "More about us" no matter if #extra is hidden or not. Why?

Upvotes: 0

Views: 281

Answers (2)

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 13974

This happens because the animation isn't done before you check the visibility. A cleaner solution would be this:

var visible = false;
$('#more').click(function() {
  visible = !visible;

  if (visible) $('#extra').slideDown();
  else $('#extra').slideUp();

  $(this).text(visible ? 'Less about us' : 'More about us');
});

Fiddle

This way you don't have to check the actual visibility of the element. You could use a callback to execute the code after the animation has completed, but that could cause an unwanted delay.

Upvotes: 0

Xposedbones
Xposedbones

Reputation: 597

the code get's executed one line at a time, so by the time you enter the if, the slideToggle isn't finished so the element is visible.

You should put the if statement inside the slideToggle's complete callback http://api.jquery.com/slidetoggle/

$('#more').click(function() {
  var _this = this;
  $('#extra').slideToggle('fast', function() {
    if($(this).is(':visible')) {
      $(_this).text('Less about us');
    }
    else {
      $(_this).text('More about us');
    }
  });
});

jsFiddle

Upvotes: 2

Related Questions