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

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, this works great. but, is there any chance I can specify the fadeout duration?
Sure, just make the duration the first argument to the fade functions. See jsfiddle.net/j08691/BdQU2/2. Ex: $("#fold_p").fadeOut(2000,function () {
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/

Comments

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

Comments

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>

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.