0

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?

colmtuite
  • 4,311
  • 11
  • 45
  • 67
  • when you click on the button for the second time old text is what currently in it, bind the current text to the element using data. https://api.jquery.com/jQuery.data/ – Millard Mar 12 '14 at 17:21
  • possible duplicate of [Button text toggle in jquery](http://stackoverflow.com/questions/13652835/button-text-toggle-in-jquery). – Ram Mar 12 '14 at 17:23

2 Answers2

4
$('.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 )

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    @Moppy - My approach had to be smart? Ug, you never mentioned that you wanted it to be smart too ;) – j08691 Mar 12 '14 at 17:39
  • Well, it was my approach really. Let's not get carried away here. All you did was move some things around :) – colmtuite Mar 12 '14 at 19:51
1

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

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

JS Fiddle

Senthilmurugan
  • 383
  • 1
  • 14