4
\$\begingroup\$

This hides div.extended then creates a button that toggles its text and div.extended's visibility.

While the below works, I was wondering if there was a more concise way of writing this code.

(function() {

var extended = $('.extended').hide();

$('<button></button>', {
    text: 'Read more'
    }).appendTo('.intro')
        .on('click', function(){
            extended.slideToggle();
        }).toggle(
            function(){
                $(this).text('Read Less')
            },
            function(){
                $(this).text('Read More')
            });

})()
\$\endgroup\$
0

1 Answer 1

4
\$\begingroup\$
$(function () {
    var extended = $('.extended').hide(),
        hidden = true;
    $('<button></button>', {
        text: 'Read more'
    }).appendTo('.intro').on('click', function () {
        extended.slideToggle();
        hidden = !hidden;
        $(this).text(hidden ? 'Read More' : 'Read Less');
    });
});

You only need to bind the click event once (toggle is a shortcut for binding to click and attaching two alternating event handlers).

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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