jQuery Toggle Text?
JqueryToggleJquery Problem Overview
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();
});
});
Jquery Solutions
Solution 1 - Jquery
$(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.
Solution 2 - Jquery
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)
Solution 3 - Jquery
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!
Solution 4 - Jquery
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');
Solution 5 - Jquery
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/
Solution 6 - Jquery
var el = $('#someSelector');
el.text(el.text() == 'view more' ? 'view less' : 'view more');
Solution 7 - Jquery
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( // );
});
Solution 8 - Jquery
Use [html()][1] to toggle HTML content. Similar to [fflyer05][2]'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/ [1]: https://api.jquery.com/html/ [2]: https://stackoverflow.com/users/398299/fflyer05
Solution 9 - Jquery
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 -------
Solution 10 - Jquery
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
Solution 11 - Jquery
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);
});
});
Solution 12 - Jquery
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");
});
Solution 13 - Jquery
$.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");
Solution 14 - Jquery
<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);
});
})();
Solution 15 - Jquery
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);
}
});
Solution 16 - Jquery
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!");
Solution 17 - Jquery
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');
Solution 18 - Jquery
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 ++ ;
}
});
Solution 19 - Jquery
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");
}
});
});
Solution 20 - Jquery
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".