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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.