Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Toggle HTML On Click

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

like image 787
John Mersal Avatar asked Mar 01 '13 09:03

John Mersal


2 Answers

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');
    });
})
like image 192
Adil Avatar answered Oct 11 '22 14:10

Adil


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

like image 23
David Hedlund Avatar answered Oct 11 '22 13:10

David Hedlund