Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Toggle .html text?

Tags:

jquery

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>');
});
});
like image 659
Yammi Avatar asked Apr 07 '11 15:04

Yammi


2 Answers

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');
})
like image 57
curiouscode Avatar answered Jan 05 '23 01:01

curiouscode


A simple solution for toggling after a click:

$('#showMore').on('click', function(){
    $(this).html() == "after" ? $(this).html('before') : $(this).html('after');
});
like image 28
user3009486 Avatar answered Jan 05 '23 00:01

user3009486