user2983258
user2983258

Reputation: 161

change value of text span in toggle

$('.post-content').each(function () {
    var count = $(this).children().length;
    if (count > 1) {
        $(this).append("<span class='more'>More</span>");
        sel = $(this).children('p').slice(2);
        sel.hide();
    }
});


$(".more").click(function () {
    more = $(this);
    sel = $(this).parent().children('p').slice(2);
    console.log($(this))
    sel.slideToggle(function () {
        more.text("More");
    }, function () {
        more.text("Less");
    });
});

This code works fine, except when I try to change the more/less. Should be more -> less -> more and I have more -> less -> less

demo

http://jsfiddle.net/Y6TaU/

Upvotes: 1

Views: 95

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

There are two things to take note of 1. slideToggle() takes 1 complete callback 2. which will be executed for every element in sel. You need to execute a single callback function where you will toggle the text when all the slide operations are completed.

For toggling the text you can use the .text(function) variant of .text(), for executing a single callback after the you can use the promise() returned by the animation.

$(".more").click(function () {
    var more = $(this);
    sel = $(this).parent().children('p').slice(2);
    sel.stop(true, true).slideToggle().promise().done(function () {
        more.text(function (_, text) {
            return text == "More" ? 'Less' : "More"
        });
    });
});

Demo: Fiddle

Upvotes: 5

SQRCAT
SQRCAT

Reputation: 5840

Refer to the jQuery documentation:

.slideToggle( [duration ] [, complete ] )

The first parameter should be the duration, the second should be a callback. You need to explicitly check for the current content of more and base your decision on that.

Upvotes: 0

Related Questions