5

I have a div with a p inside it that says 'Fold it!'. When I click the div, the p's text changes to 'Expand it'. How can I make so when I click the div for the second time it will change back to 'Fold it'?

HTML:

<div id="fold">
    <p id="fold_p">Fold it</p>
</div>

JQuery:

<script>
  $(document).ready(function () {
    $("#fold").click(function () {
      $("#fold_p").text("Expand it");
    } )
  } );                  
</script>

Also, is it possible to make the transition a fade? Any help is much appreciated :)

Phil Ross
  • 25,590
  • 9
  • 67
  • 77
Shaul Bar-Lev
  • 95
  • 2
  • 2
  • 9
  • 1
    possible duplicate of [Button text toggle in jquery](http://stackoverflow.com/questions/13652835/button-text-toggle-in-jquery) – Ram Jan 30 '14 at 14:49

4 Answers4

11
$(document).ready(function () {
    $("#fold").click(function () {
        $("#fold_p").fadeOut(function () {
            $("#fold_p").text(($("#fold_p").text() == 'Fold it') ? 'Expand it' : 'Fold it').fadeIn();
        })
    })
});

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Wow, this works great. but, is there any chance I can specify the fadeout duration? – Shaul Bar-Lev Jan 30 '14 at 15:03
  • Sure, just make the duration the first argument to the fade functions. See http://jsfiddle.net/j08691/BdQU2/2/. Ex: `$("#fold_p").fadeOut(2000,function () {` – j08691 Jan 30 '14 at 15:04
0
jQuery ("#fold")    .click (function () {
        if (jQuery (this).children ("#fold_p").text() == "Fold it") {
                jQuery (this).children ("#fold_p").text("Expand It");
        }
        else {
             jQuery (this).children ("#fold_p").text("Fold it");        
        }
    });

Above is the sample code for your question.

Here is the fiddle link: http://jsfiddle.net/teZQA/

0

Fiddle Demo

$(document).ready(function () {
    var fold = $("#fold");
    fold.cliked = 1;// set initial click value to 1
    fold.click(function () {
    //change text o base of even or odd
        $("#fold_p").text((fold.cliked++ % 2 == 0) ? "Fold it" : "Expand it");
    });
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

try this:

<script>
$(document).ready(function () {
  $("#fold").click( function (){
    if($(this).hasClass("helperClass")){
     $(this).find("p").text("Expand it");

    }else{
      $(this).find("p").text("Fold it");
    }
    $(this).toggleClass("helperClass");
  });
});                  
</script>
Rami.Q
  • 2,486
  • 2
  • 19
  • 30