egr103 egr103 - 7 months ago 14
Javascript Question

Toggle text when link is clicked

I have the below code that toggles a div (called

#extra
) into view:

$('#more').click(function() {
$('#extra').slideToggle('fast');
return false;
});


My click function is this link:

<a href="#" id="more">More about us</a>


How do I get that 'More about us' text to change to read 'Less about us' when the
#extra
div is visible? When the same link is clicked to hide the div, I'd like the text of the link to change back to read 'More about us'.

Answer

Just toggle the text ?

$('#more').click(function() {
    $('#extra').slideToggle('fast');
    $('#more').text(function(_,txt) {
        var ret='';

        if ( txt == 'More about us' ) {
           ret = 'Less about us';
           $(this).css('background','url(link/to/image1.png)');
        }else{
           ret = 'More about us';
           $(this).css('background','url(link/to/image2.png)');
        }
        return ret;
    });
    return false;
});