colmtuite
colmtuite

Reputation: 4491

Toggle span text on click with jQuery

I'm trying to write a reusable script for toggling the text of an element on click.

I have it working on click but I can't get it to toggle back. Is there something wrong with my if statement?

<span class="js-textEdit" data-text="Show less">Show more</span>


$('.js-textEdit').click(function() {
  var oldText = $(this).text();
  var newText = $(this).attr('data-text');

  if ($(this).text(oldText)) {
    $(this).text(newText);
  } else {
    $(this).text(oldText);
  }
});

Here's a JSFIddle

Also, is there a cleaner way to refactor this? Rather than use IDs and have to write a separate script for every element I want to use it on, I'm using a data attribute to determine the new text. Is the data attribute method a good approach?

Upvotes: 0

Views: 3471

Answers (2)

j08691
j08691

Reputation: 207891

$('.js-textEdit').click(function () {
    var oldText = $(this).text();
    var newText = $(this).data('text');
    $(this).text(newText).data('text',oldText);
});

jsFiddle example (and a slightly better example to show how it works on multiple elements )

Upvotes: 4

Senthilmurugan
Senthilmurugan

Reputation: 383

You have to set the data-set to old text.

   $(this).attr('data-text',oldText);

JS Fiddle

Upvotes: 1

Related Questions