83

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();
    });
});
Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
mtwallet
  • 5,040
  • 14
  • 50
  • 74

20 Answers20

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

Kyle Butt
  • 9,340
  • 3
  • 22
  • 15
74

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)

JxAxMxIxN
  • 1,711
  • 1
  • 17
  • 20
  • 3
    Brilliant solution! You can change `text` to `html` and toggle classes to use this function as a read more/read less function :) – Meules Feb 09 '17 at 17:34
  • Sure could! In web-apps and cases where you don't need to worry about the text being found by search engines this is a great solution. Just keep in mind that if the content in the "read more" section could actually help website ranking in search engines due to its content, this might not be the best option. – JxAxMxIxN Feb 09 '17 at 22:15
  • Mate, you are my personal hero for this! Thank you. – Mego May 24 '22 at 18:45
37

Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".

Will check more thoroughly next time before I ask!

My code is now:

$(function() {
  $("#show-background").toggle(function (){
    $("#content-area").animate({opacity: '0'}, 'slow')
    $("#show-background").text("Show Text")
      .stop();
  }, function(){
    $("#content-area").animate({opacity: '1'}, 'slow')
    $("#show-background").text("Show Background")
      .stop();
  });
});

Thanks again for the help!

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
mtwallet
  • 5,040
  • 14
  • 50
  • 74
  • 17
    Readers, beware! This overload of `toggle` function was removed in jQuery 1.9, you won't be able to use it unless you [restore this functionality](http://stackoverflow.com/questions/14301935/where-has-fn-toggle-handlereventobject-handlereventobject-gone). But perhaps it is better if you proceed to other answers. – user Mar 02 '14 at 08:26
26

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');
Diego Favero
  • 1,969
  • 2
  • 22
  • 32
  • 1
    @webkitfanz change **text** in places like *that.text(a)* to **html**, simple. See -> $.fn.extend({ toggleText: function(a, b){ return this.html(this.html() == b ? a : b); } }); – Vishwa Aug 16 '19 at 08:20
16
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/

Nate-Wilkins
  • 5,364
  • 4
  • 46
  • 61
  • 1
    This was very easy to implement. At first I wasn't sure it would do the trick because my click action also fires a slideToggle, but it did the trick with no issues. It's great for "show Text"/"Hide Text" uses. Thanks! – acarito Mar 24 '14 at 07:22
16
var el  = $('#someSelector');    
el.text(el.text() == 'view more' ? 'view less' : 'view more');
Judson Terrell
  • 4,204
  • 2
  • 29
  • 45
7

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( // );
});
  • 5
    This implementation of toggle was removed from Jquery v1.9, it now toggles visibility. See [here](http://api.jquery.com/toggle-event/) – solipsicle Mar 18 '14 at 18:57
6

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/

Community
  • 1
  • 1
Tomasz Majerski
  • 199
  • 2
  • 7
4

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 -------
3

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

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

     if (altText) {
      this.data("alt-text", this.html());
      this.html(altText);
     }
    };

    $('[data-toggle="offcanvas"]').click(function ()  {

     $(this).toggleText();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>

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

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
2

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);
 });
});
Community
  • 1
  • 1
Mottie
  • 84,355
  • 30
  • 126
  • 241
  • Wow will take me a bit work how this is working but thanks for the help I will try it out! – mtwallet Jan 28 '10 at 15:26
  • BTW I have now linked to jQuery 1.4 and broken down the Tools library isolating only the parts I need. I think the conflict was with the Flash Embed part of the library. – mtwallet Jan 28 '10 at 15:28
  • In case you didn't know, the `o` and `t` are defined in a ternary operator (http://en.wikipedia.org/wiki/Ternary_operation).... and oops I forgot to add `var` in front - I will edit that now – Mottie Jan 29 '10 at 14:07
1

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");
});
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
fflyer05
  • 873
  • 11
  • 18
1
$.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");
RulazISC
  • 11
  • 1
1
<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);
    });

})();
1

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);
    }
});
Andi
  • 3,249
  • 1
  • 20
  • 12
1

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!");
Yurii Rabeshko
  • 591
  • 8
  • 17
1

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');
Ricky Levi
  • 7,298
  • 1
  • 57
  • 65
0

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 ++ ;
     }

});
Erez Lieberman
  • 1,893
  • 23
  • 31
0

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");
        }
    });
});
ortonomy
  • 653
  • 10
  • 18
0
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".

mriiiron
  • 117
  • 4