Why won't this work?
HTML
<a href="#" id="showMore">Before</a>
JS
$('#showMore').click(function() {
$(this).toggle(
function () {
$(this).html('<a href="#">After</a>');},
function () {
$(this).html('<a href="#">Before</a>');
});
});
Why won't this work?
HTML
<a href="#" id="showMore">Before</a>
JS
$('#showMore').click(function() {
$(this).toggle(
function () {
$(this).html('<a href="#">After</a>');},
function () {
$(this).html('<a href="#">Before</a>');
});
});
Blender has the appropriate answer, but we can also generalize your question into a simple jQuery plugin:
$.fn.toggleText = function(t1, t2){
if (this.text() == t1) this.text(t2);
else this.text(t1);
return this;
};
Your code would then look like:
$('#showMore').click(function(){
$(this).toggleText('Before', 'After');
})
A simple solution for toggling after a click:
$('#showMore').on('click', function(){
$(this).html() == "after" ? $(this).html('before') : $(this).html('after');
});
$(this).html(($(this).html() == "after") ? 'before' : 'after')Not sure what's up with JsFiddle.net, but I can't post a demo.
You're nesting two functions within each other (.click() and .toggle()), and .toggle() handles a click, so that might be causing conflict. Also, use text() instead of html():
HTML:
<a href="#" id="showMore">Before</a>
JavaScript:
$('#showMore').toggle(function() {
$(this).text('Before');
}, function() {
$(this).text('After');
});
This is a reduced / "more compact" version of the same answer here: "A simple solution for toggling after a click".
$('#showMore').on('click', function(){
$(this).html($(this).html() == 'after' ? 'before' : 'after');
});
Of course this needs jQuery plugin for it to work.
You are binding a click to the <a/> and than inside of that you are binding a toggle() to it.
If you simply want to toggle you can leave off the click().
$('#showMore').toggle(
function() {
$(this).html('<a href="#">After</a>');
},
function() {
$(this).html('<a href="#">Before</a>');
});
With that being said you are placing an <a/> inside of another <a/> Is that really what you want? Or you you just want to replace the .text()? .text("Before")
because you are nesting a <a> inside another, resulting in something like <a href="#" id="#showMore"><a href="">After</a></a>
You should just use $(this).text('After') and same with Before
I guess you wanted to use replaceWith() which is not very efficient in this situation because only the text changes.
++ the toggle bug spotted in the other answers. Kudos to them ;-)
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');