Reputation: 4491
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
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
Reputation: 383
You have to set the data-set to old text.
$(this).attr('data-text',oldText);
Upvotes: 1