Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div text with jQuery Toggle

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/

like image 659
olo Avatar asked Oct 18 '12 07:10

olo


People also ask

How do you toggle text on a button click?

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.

What is toggle () in jQuery?

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().


1 Answers

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');                         }             });        }); 
like image 88
danwellman Avatar answered Sep 30 '22 09:09

danwellman