Raymond G
Raymond G

Reputation: 39

Toggle show/hidden with jquery

I need to use jquery to toggle two elements to show/hide. I want the button to say "hide text" and change to "show text" when it is clicked and of course I want the text to toggle from show to hide as the button is clicked. I have this to change it one time but I do not know how to change it back or make it toggle.

$(function() {
    $('button#1').click(function() {
        $('#one').fadeOut();
    });

    $('button#1').click(function() {
        $('button#1').html('Show Text');
    });
});

Upvotes: 0

Views: 176

Answers (4)

Flo Schild
Flo Schild

Reputation: 5304

http://jsfiddle.net/fwdzm/1/

Use the toggle callbacks !

$(function() {
    var $btn1 = $('button#1').click(function() {
        $('#one').toggle('slow', function () {
            if ($(this).is(':visible')) {
                $btn1.html('Hide Text');
            } else {
                $btn1.html('Show Text');
            }
        });
    });
});

Upvotes: 6

Deratrius
Deratrius

Reputation: 689

Save the current state in a variable and then based on that variable you either show or hide your elements and change the text on the button.

HTML

<button id="toggleBtn" type="button">Hide Text</button>
<span id="element">Your text is here</span>

JAVASCRIPT

var status = "shown";

function toggleElement() {
    if (status == "shown") {
        $('#element').hide();
        $("#toggleBtn").html('Show Text');
        status = "hidden";
    } else {
        $('#element').show();
        $("#toggleBtn").html('Hide Text');
        status = "shown";
    }
}

Upvotes: 0

Ivan K
Ivan K

Reputation: 31

Try something like this

$(function() {
  $('button#1').click(function(){
    if ($('#one').is(':visible')) {
      $('#one').fadeOut();
      $(this).html('Show Text');
    } else {
      $('#one').fadeIn();
      $(this).html('Hide Text');
    }
  });
});

Upvotes: 0

lucuma
lucuma

Reputation: 18339

$('button#1').click(function() {
    var $btn = $(this);
    $('#one').toggle('slow', function() {
       if ($(this).is(':visible')) {
          $btn.text('Hide');
       } else {
          $btn.text('Show Text');
       }
    });
});

Upvotes: 3

Related Questions