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?

2
  • 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. api.jquery.com/jQuery.data Commented Mar 12, 2014 at 17:21
  • possible duplicate of Button text toggle in jquery. Commented Mar 12, 2014 at 17:23

2 Answers 2

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 )

Sign up to request clarification or add additional context in comments.

2 Comments

@Moppy - My approach had to be smart? Ug, you never mentioned that you wanted it to be smart too ;)
Well, it was my approach really. Let's not get carried away here. All you did was move some things around :)
1

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

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

JS Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.