4

i'm trying to display a paragraph of text and then underneath is a "read more" link, when i click the link, more text is supposed to slide down and the text of the link is supposed to read "Read Less", then when they click that, the text is supposed to slide back up and the link text to be "Read More" again..

$('#more').click(function() {
                $('#the_more').slideToggle("slow", function () {
                      $('#more').html("Read Less");
                    });
});

Anyone spot any problems?

2
  • Well the wording gets changed in one direction only, so it'll never return to "Read More". Other than that, it would be nice to see the HTML that accompanies this.
    – Orbling
    Commented Nov 27, 2010 at 18:46
  • looks right to me, but I suppose you must be having problems if you post this? Where is this code? Commented Nov 27, 2010 at 18:48

1 Answer 1

6

From my comment:

Well the wording gets changed in one direction only, so it'll never return to "Read More". Other than that, it would be nice to see the HTML that accompanies this.

Here is some code that might work, pending seeing the HTML.

$('#more').click(function() {
    $('#the_more').slideToggle("slow", function () {
        $('#more').text(function (index, text) {
            return (text == 'Read More' ? 'Read Less' : 'Read More');
        });
    });

    return false;
});

Demo: http://jsfiddle.net/yLvms/

The code works as follows.

  1. A click event is bound to the #more element, when clicked the function fires.
  2. When fired, #the_more element is slid up or down, toggled, depending on it's visibility state.
  3. A callback is fired after the slideToggle() is finished that changes the text
  4. The text within #the_more is changed using the functional variant of the .text() function, this passes the current text value to the function for changing.
  5. The text function is simply a ternary-if that checks the current value of the text within #the_more and if it is currently 'Read More' it becomes 'Read Less' and vice versa, a toggle of the text.

Hope that helps.

4
  • Almost! Except its putting the "Read More" and "Read Less" the wrong way round?? Commented Nov 27, 2010 at 18:52
  • Got it now, great code, would you mind explaining it a bit more, especially the return text line... Commented Nov 27, 2010 at 18:59
  • Well are you starting off with Read More on the first click?
    – Orbling
    Commented Nov 27, 2010 at 19:05
  • I've expanded my answer with a full explanation and a demo in jsfiddle, for you to play with.
    – Orbling
    Commented Nov 27, 2010 at 19:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.