6

When i click on the button the HTML changes, But when i click again, the slide toggle fires up but the I want to put back 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 is that done?

Thank you

4 Answers 4

24

You can use conditional operator ? : to switch between texts.

Live Demo

$(document).ready(function(){
    $("#show").click(function(){
        $('#visible').slideToggle();            
        $('#show').html($('#show').text() == 'Hide me' ? 'Show Me' : 'Hide me');
    });
})
Sign up to request clarification or add additional context in comments.

1 Comment

Well that was pretty quick :) That did the trick :) Thank you so much :)
2

You need to pass 'Show me' or 'Hide me' to .html, depending on whether you're showing or hiding. One way would be to check the visibility of #visible before sliding:

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

and consequently:

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

Demo

Comments

0

Look at this solution too:

$("#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/

2 Comments

I actually did that the 1st time, but i didnt wanna add class and remove class. i wanned the best way to switch between html text because i dont have experience with it, but now i understand how it works :)
I prefer using slideUp and slideDown instead of slideToggle, because this way you can be sure that it slides down when the text just became 'hide me' and vice versa. Slidetoggle is not so clear, because just by looking at the code, you can't tell what will happen, it depends on the actual state, it can be confusing.
0

use a 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.