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\$
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\$
  • \$\begingroup\$ Many thanks Mr Barry. I've learnt something today. \$\endgroup\$ – NickSheehy Apr 30 '12 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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