JQuery - Toggle .html text?
Not sure with JsFiddle.net, but I can not post a demo.
You insert two functions inside each other ( .click() and .toggle() ), and .toggle() handles click , so this can cause a 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'); }); The blender has a corresponding 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; }; Then your code will look like this:
$('#showMore').click(function(){ $(this).toggleText('Before', 'After'); }) You bind click to <a/> , not inside the fact that you bind toggle() to it.
If you just want to switch, you can leave click() .
$('#showMore').toggle( function() { $(this).html('<a href="#">After</a>'); }, function() { $(this).html('<a href="#">Before</a>'); }); With that said, you put <a/> inside another <a/> . Is this really what you want? Or do you just want to replace .text() ? .text("Before")
because you insert <a> inside another, which leads to something like <a href="#" id="#showMore"><a href="">After</a></a>
You should just use $(this).text('After') and the same with Before
I think you wanted to use replaceWith() , which is not very efficient in this situation, because only the text changes.
++ switching error in other answers. Kudos to them; -)
This is a shortened version with a more compact version of the same answer: "A simple solution to switch after a click . "
$('#showMore').on('click', function(){ $(this).html($(this).html() == 'after' ? 'before' : 'after'); }); Of course, this requires a jQuery plugin to work.
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');