Shaul Bar-Lev
Shaul Bar-Lev

Reputation: 95

JQuery change text on click (Also change back)

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 :)

Upvotes: 5

Views: 52022

Answers (4)

Rami.Q
Rami.Q

Reputation: 2476

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>

Upvotes: 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");
    });
});

Upvotes: 0

Arunkumar Srisailapathi
Arunkumar Srisailapathi

Reputation: 1169

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/

Upvotes: 0

j08691
j08691

Reputation: 207861

$(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

Upvotes: 11

Related Questions