I've got a 3 items that are clickable and need to have the text changed on click.
the HTML
<div class="aaa">
<p class="bbb">Hello</p>
</div>
<div class="aaa">
<p class="bbb">Hello</p>
</div>
<div class="aaa">
<p class="bbb">Hello</p>
</div>
and the jQuery
$('.aaa').on("click", function() {
$('.bbb', this).text(function(_, oldText) {
return oldText === 'Hello' ? 'Goodbye' : 'Hello';
});
return false;
});
My problem is I need to 'reset' the text if I click a different item. What do I need for this?
Here's the work so far on CodePen - http://codepen.io/sturobson/pen/zbunG
You can add
data-*
attribute to the elements and store the original texts in those attributes;http://codepen.io/anon/pen/LDudE
I recommend you make it flexible and use data- attributes so as not to limit the strings to those stored in JS, and also consider performance by not traversing the dom every time.
HTML:
JS:
Working example: http://codepen.io/stowball/pen/uBqlE
Try this: Demo http://jsfiddle.net/ZPaU6/
APIs in use:
.find
- http://api.jquery.com/find/Rest this should help the cause I reckon
:)
CodeTry
Demo: Fiddle