[jquery] jQuery Toggle Text?

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();
    });
});

This question is related to jquery toggle

The answer is


Perhaps I'm oversimplifying the problem, but this is what I use.

$.fn.extend({
    toggleText: function(a, b) {
        $.trim(this.html()) == a ? this.html(b) : this.html(a);
    }
});

You can also toggleText by using toggleClass() as a thought ..

.myclass::after {
 content: 'more';
}
.myclass.opened::after {
 content: 'less';
}

And then use

$(myobject).toggleClass('opened');

Use html() to toggle HTML content. Similar to fflyer05's code:

$.fn.extend({
    toggleText:function(a,b){
        if(this.html()==a){this.html(b)}
        else{this.html(a)}
    }
});

Usage:

<a href="#" onclick='$(this).toggleText("<strong>I got toggled!</strong>","<u>Toggle me again!</u>")'><i>Toggle me!</i></a>

Fiddle: http://jsfiddle.net/DmppM/


Nate-Wilkins's improved function:

jQuery.fn.extend({
    toggleText: function (a, b) {
        var toggle = false, that = this;
        this.on('click', function () {
            that.text((toggle = !toggle) ? b : a);
        });
        return this;
    }
});

html:

<button class="button-toggle-text">Hello World</button>

using:

$('.button-toggle-text').toggleText("Hello World", "Bye!");

The most beautiful answer is... Extend jQuery with this function...

$.fn.extend({
    toggleText: function(a, b){
        return this.text(this.text() == b ? a : b);
    }
});

HTML:

<button class="example"> Initial </button>

Use:

$(".example").toggleText('Initial', 'Secondary');

I've used the logic ( x == b ? a : b ) in the case that the initial HTML text is slightly different (an extra space, period, etc...) so you'll never get a duplicate showing of the intended initial value

(Also why I purposely left spaces in the HTML example ;-)

Another possibility for HTML toggle use brought to my attention by Meules [below] is:

$.fn.extend({
        toggleHtml: function(a, b){
            return this.html(this.html() == b ? a : b);
        }
    });

HTML:

<div>John Doe was an unknown.<button id='readmore_john_doe'> Read More... </button></div>

Use:

$("readmore_john_doe").click($.toggleHtml(
    'Read More...', 
    'Until they found his real name was <strong>Doe John</strong>.')
);

(or something like this)


jQuery.fn.extend({
        toggleText: function (a, b){
            var isClicked = false;
            var that = this;
            this.click(function (){
                if (isClicked) { that.text(a); isClicked = false; }
                else { that.text(b); isClicked = true; }
            });
            return this;
        }
    });

$('#someElement').toggleText("hello", "goodbye");

Extension for JQuery that only does toggling of text.

JSFiddle: http://jsfiddle.net/NKuhV/


<h2 id="changeText" class="mainText"> Main Text </h2>

(function() {
    var mainText = $('.mainText').text(),
        altText = 'Alt Text';

    $('#changeText').on('click', function(){
        $(this).toggleClass('altText');
        $('.mainText').text(mainText);
        $('.altText').text(altText);
    });

})();

In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:

$.fn.extend({
  toggleText: function (a, b){
    if (this.text() == a){ this.text(b); }
    else { this.text(a) }
  }
);

You could use it this way:

$(document).on('click', '.toggle-details', function(e){
  e.preventDefault();
  //other things happening
  $(this).toggleText("Show Details", "Hide Details");
});

Why not keep track of the state of through a class without CSS rules on the clickable anchor itself

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow');
        $("#show-background").toggleClass("clicked");
        if ( $("#show-background").hasClass("clicked") ) {
            $(this).text("Show Text");
        }
        else {
            $(this).text("Show Background");
        }
    });
});

var jPlayPause = $("#play-pause");
jPlayPause.text(jPlayPause.hasClass("playing") ? "play" : "pause");
jPlayPause.toggleClass("playing");

This is a piece of thought using jQuery's toggleClass() method.

Suppose you have an element with id="play-pause" and you want to toggle the text between "play" and "pause".


$.fn.toggleText = function(a){
    var ab = a.split(/\s+/);
    return this.each(function(){
        this._txIdx = this._txIdx!=undefined ? ++this._txIdx : 0;
        this._txIdx = this._txIdx<ab.length ? this._txIdx : 0; 
        $(this).text(ab[this._txIdx]);
    }); 
}; 
$('div').toggleText("Hello Word");

$(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.


Why don't you just stack them ::

$("#clickedItem").click(function(){
  $("#animatedItem").animate( // );
}).toggle( // <--- you just stack the toggle function here ...
function(){
  $(this).text( // );
},
function(){
  $(this).text( // );
});

I've written my own little extension for toggleText. It may come in handy.

Fiddle: https://jsfiddle.net/b5u14L5o/

jQuery Extension:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
                                                    : $(this).text(stateOne);
        });  
    }
});

Usage:

...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------

//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------

//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------

//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------

var el  = $('#someSelector');    
el.text(el.text() == 'view more' ? 'view less' : 'view more');

Use this

jQuery.fn.toggleText = function() {
    var altText = this.data("alt-text");
    if (altText) {
        this.data("alt-text", this.html());
        this.html(altText);
    }
};

Here is how you sue it

_x000D_
_x000D_
 _x000D_
   jQuery.fn.toggleText = function() {_x000D_
     var altText = this.data("alt-text");_x000D_
_x000D_
     if (altText) {_x000D_
      this.data("alt-text", this.html());_x000D_
      this.html(altText);_x000D_
     }_x000D_
    };_x000D_
_x000D_
    $('[data-toggle="offcanvas"]').click(function ()  {_x000D_
_x000D_
     $(this).toggleText();_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>
_x000D_
_x000D_
_x000D_

You can even use html provided it's html encoded properly


Improving and Simplifying @Nate's answer:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');

this is not the very clean and smart way but its very easy to understand and use somtimes - its like odd and even - boolean like:

  var moreOrLess = 2;

  $('.Btn').on('click',function(){

     if(moreOrLess % 2 == 0){
        $(this).text('text1');
        moreOrLess ++ ;
     }else{
        $(this).text('more'); 
        moreOrLess ++ ;
     }

});

Modifying my answer from your other question, I would do this:

$(function() {
 $("#show-background").click(function () {
  var c = $("#content-area");
  var o = (c.css('opacity') == 0) ? 1 : 0;
  var t = (o==1) ? 'Show Background' : 'Show Text';
  c.animate({opacity: o}, 'slow');
  $(this).text(t);
 });
});