Yammi Yammi - 2 months ago 18
jQuery Question

jQuery - Toggle .html text?

Why won't this work?

http://jsfiddle.net/PdwJ6/

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>');
});
});

Answer

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');
});