When using slideToggle
, how to change the Text close/show? I did a simple one, but cannot get the text change back.
Here is what I did:
$(document).ready(function(){ $('.open').click(function(){ $('.showpanel').slideToggle('slow'); $(this).text('close'); }); $('.open2').click(function(){ $('.showpanel2').slideToggle('slow'); $(this).text('close'); }); });
body{ font-size:20px; } #box{ border:2px solid #000; width:500px; min-height:300px; } .open,.open2 { width:450px; height:50px; background:blue; margin:5px auto 0 auto; color:#fff; } .showpanel,.showpanel2{ width:450px; height:300px; margin:0 auto 10px auto; background:red; display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box"> <div class="open">Show</div> <div class="showpanel">This is content</div> <div class="open2">Show</div> <div class="showpanel2">This is content</div> </div>
http://jsfiddle.net/9EFNK/
To toggle a button's text on click:Add a click event listener to the button. Each time the button is clicked, check if the button's text is the initial text. If it is, change the text to the clicked text.
The toggle() method attaches two or more functions to toggle between for the click event for the selected elements. When clicking on an element, the first specified function fires, when clicking again, the second function fires, and so on. Note: There is also a jQuery Effects method called toggle().
You can use the is()
assertion method to check whether the panel is open or closed in the animation's callback and set the text accordingly - http://jsfiddle.net/9EFNK/7/
$('.open').click(function(){ var link = $(this); $('.showpanel').slideToggle('slow', function() { if ($(this).is(':visible')) { link.text('close'); } else { link.text('open'); } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With