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