Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 221
Shaul Bar-Lev Avatar asked Jan 30 '14 14:01

Shaul Bar-Lev


People also ask

Which method is used to change text that appears on button?

Answer: Use the jQuery prop() and html() Methods You can simply use the jQuery prop() method to change the text of the buttons built using the HTML <input> element, whereas to change the text of the buttons which are created using the <button> element you can use the html() method.

What is difference between click and Onclick in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.


1 Answers

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

like image 87
j08691 Avatar answered Oct 29 '22 20:10

j08691