Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Juliana Madrone
Juliana Madrone
8,552 Points

When using a button to load text with AJAX, is it possible to then use the same button to unload that text?

Here's the relevant code I'm using to load the text and change the button text:

<script>
    function sendAJAX() { 
      $('#ajax').load('firstessay.html');
      $('#essay1').html('Read Less');
    } 
  </script>

<section id="ajax">

</section>
          <p><button id="essay1" onclick="sendAJAX()" class="load">Read More</button></p>

This is working fine, I'm just not sure how to proceed. Thanks for any clues. Juliana

Dylan Shine
Dylan Shine
17,565 Points

Hi Juliana,

In terms of "unloading", what exactly do you mean?

4 Answers

Dylan Shine
Dylan Shine
17,565 Points

Hi Juliana, You shouldn't be using AJAX for that. AJAX should be used when you're sending/receiving data from a server; the solution can be solved with pure jQuery.

$("#essay1").on('click', function(event) {
    var $target = $(event.target);
    $target.text($target.text() === "read more" ? "read less" : "read more");
  });

Best, Dylan

Juliana Madrone
Juliana Madrone
8,552 Points

I'm using AJAX to make a large chunk of text appear on the webpage, and then I'd like to be able to make that text disappear when the user clicks a button. I'm just not sure how to accomplish that part, or if it's possible with only AJAX.

Dylan Shine
Dylan Shine
17,565 Points

Oh, that's easy. During the .done() of your AJAX call, grab the html element with jQuery and either hide the entire element with .hide() or change the text of the element using .text() to whatever you want.

Juliana Madrone
Juliana Madrone
8,552 Points

Sorry Dylan, I'm not sure I was clear, or I'm not understanding your answer. The user makes the text appear by clicking a button. I'd like for them to click the same button and be able to make the text disappear again. I've gotten the button to change from saying "read more" to "read less" but I can't get the functionality to change. Does it need another function? or?

Juliana Madrone
Juliana Madrone
8,552 Points

Thanks Dylan, I was afraid of that!