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
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:
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:
John Doe was an unknown.
Use:
$("readmore_john_doe").click($.toggleHtml(
'Read More...',
'Until they found his real name was Doe John.')
);
(or something like this)