Joe W
Joe W

Reputation: 259

Restore Previous value when another element is clicked

I have multiple elements each element is a tile, every element has text in it and when the user clicks on each tile it changes the text. I have one JavaScript function which handles this and it works but I would like to make it so that only one tile can have the changed text at a time. When the next element is clicked the previous should return to the default text. Below is my code. The text in the P tag is the default text.

 <div class="page" title="Page 2" onClick="changeText('Some text blah blah blah.','home-grid-one-one')">
    <p>Understandable</p>
  <div class="page" title="Page 2" onClick="changeText('Some different text blah blah blah.','home-grid-one-two')">
    <p>Measurable</p>

function changeText(text, ele) {
    var display = document.getElementById(ele);
    display.style.textAlign = "center";
    display.style.fontSize = "1em";
    display.innerHTML = text;
}

Upvotes: 0

Views: 371

Answers (1)

Sarvap Praharanayuthan
Sarvap Praharanayuthan

Reputation: 4360

Well I would like to suggest a simple solution. Usage of data attributes.

Tiles:

<p class='tile' data-default="The default text 1 here" data-clicked="Text to be replaced">The default text 1 here</p>

<p class='tile' data-default="The default text 2 here" data-clicked="Text to be replaced">The default text 2 here</p>

<p class='tile' data-default="The default text 3 here" data-clicked="Text to be replaced">The default text 3 here</p>

jQuery:

$('.tile').click(function(e) { // when the tile is clicked
    $('.tile').not(this).text($(this).attr('data-default')); // Except the clicked tile all are restored to default data
    $(this).text($(this).attr('data-clicked')); // The clicked tile gets the replacer text
});

If your replacer text contains HTML in it, use .html() instead of .text()

Upvotes: 2

Related Questions