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
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( // );
});
$.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");
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
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!");
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".
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');