Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.

like image 737
egr103 Avatar asked Nov 30 '22 01:11

egr103


2 Answers

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/

like image 126
Nishu Tayal Avatar answered Dec 09 '22 18:12

Nishu Tayal


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;
});
like image 32
adeneo Avatar answered Dec 09 '22 20:12

adeneo