Toggle text when link is clicked

egr103 picture egr103 · Jul 18, 2013 · Viewed 28.2k times · Source

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

Nishu Tayal picture Nishu Tayal · Jul 18, 2013

Use this code :

$('#more').click(function() {
    jQuery(this).text('less about us');
    if($('#extra').is(':visible')){
          jQuery(this).text('Less about us');
    }else{
          jQuery(this).text('More about us');
    }
    $('#extra').slideToggle('fast');
    return false;
});

Here is the demo : http://jsfiddle.net/AAFaY/