JQuery Toggle HTML on click

When I click the button, the HTML changes, But when I click again, the slide switch switches, but I want to return the html as Show Me.

<div id="show">Show Me</div> <div id="visible">Hello, My name is John.</div> $(document).ready(function(){ $("#show").click(function(){ $('#visible').slideToggle(); $('#show').html('Hide me'); }); }) 

http://jsfiddle.net/u2p48/13/

Any idea how to do this?

thanks

+6
source share
4 answers

Can you use a conditional statement ? : ? : to switch between texts.

Live demo

 $(document).ready(function(){ $("#show").click(function(){ $('#visible').slideToggle(); $('#show').html($('#show').text() == 'Hide me' ? 'Show Me' : 'Hide me'); }); }) 
+20
source

You need to pass 'Show me' or 'Hide me' in .html , depending on whether you show or hide. One way is to check #visible visibility before gliding:

 var on = $('#visible').is(':visible'); 

and therefore

 $('#show').html(on ? 'Show me' : 'Hide me'); 

Demo

+2
source

Take a look at this solution:

 $("#show").click(function(){ if ($('#visible').hasClass('visible')) { $('#visible').slideDown().removeClass('visible'); $('#show').html('Hide me'); } else { $('#visible').slideUp().addClass('visible'); $('#show').html('Show Me'); } }); 

http://jsfiddle.net/xkyf2/1/

0
source

use the data attribute in your html

  $('button').on('click', function(){ var that = $('button'); if(that.text() == that.data("text-swap")){ that.text(that.data("text-original")); } else { that.data("text-original", that.text()); that.text(that.data("text-swap")); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button data-text-swap="Replace Text" data-text-original="Original Text">Original Text</button> 
0
source

All Articles