jQuery Toggle Text?

mtwallet picture mtwallet · Jan 28, 2010 · Viewed 164k times · Source

How to toggle HTML text of an anchor tag using jQuery? I want an anchor that when clicked the text alternates between Show Background & Show Text as well as fading in & out another div. This was my best guess:

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    $("#show-background").toggle(function (){
        $(this).text("Show Background")
        .stop();
    }, function(){
        $(this).text("Show Text")
        .stop();
    });
});

Answer

Kyle Butt picture Kyle Butt · Jan 28, 2010
$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    var text = $('#show-background').text();
    $('#show-background').text(
        text == "Show Background" ? "Show Text" : "Show Background");
});

Toggle hides or shows elements. You could achieve the same effect using toggle by having 2 links and toggling them when either is clicked.