Domanda

I have this simple jquery slide that I want to have only one button. If the div is being shown, the show button will become a hide button. And if the div is hidden, the hide button will become a show button.

Currently, mine has a separate show and hide buttons. I don't know how to merge this buttons into one. I hope someone here can help me. :(

    <script type="text/javascript" 
    src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript" 
    src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script type="text/javascript" language="javascript">

     $(document).ready(function() {

       $("#hide").click(function(){
          $(".target").hide( "slide", 
                      { direction: "up"  }, 500 );
       });

       $("#show").click(function(){
          $(".target").show( "slide", 
                       {direction: "up" }, 500 );
       });

    });
    </script>
    <style>

      div{ width:100%; 
             height:100px; 
             background: #000; 
             color: #fff; 
         }
   </style>
 </head>

 <div class="target" style="display:none;">
 My Bag Items
 <button id="hide">Hide My Bag</button>
 </div>
 <button id="show">My Bag</button> 
È stato utile?

Soluzione

$("#toggle").click(function(){
    var $target = $('.target'),
        $toggle = $(this);

    $target.slideToggle( 500, function () {
        $toggle.text(($target.is(':visible') ? 'Hide' : 'Show') + ' My Bag');
    });
});

Demo : http://jsfiddle.net/qmK26/

Altri suggerimenti

New markup -

<div class="target">My Bag Items</div>
<button id="togButton">Hide</button>

jQuery

$('#togButton').click(function() {
    $('.target').slideToggle(500);
    if( $(this).text() == 'Hide' ) {
        $(this).text('Show');
    } else {
        $(this).text('Hide');
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top