Brandon Leung Brandon Leung - 3 months ago 15
Javascript Question

How to change content on click, and change previously clicked content to previous state

How can I properly solve this problem using vanilla JS (not jQuery), by attaching a click handler? Code & requirements are below:

function clickHandler() {

}

// Widget's HTML code:
<table id="card-container">
<tbody>
<tr>
<td class="card">down</td>
<td class="card">down</td>
</tr>
<tr>
<td class="card">down</td>
<td class="card">down</td>
</tr>
</tbody>
</table>



  1. Clicking on a card will change it's content to "up"

  2. Clicking on a next card, will change it's content to "up", and the previously clicked card will change it's content to "down"

  3. Only 1 card at a time can ever be "up"

  4. Create a click handler that will solve this with vanilla JS. The HTML cannot be modified.


Answer

function clickHandler() {
  var cards=document.getElementsByClassName("card");
  for(var i=0;i<cards.length;i++){
     cards[i].innerHTML = "down";
  }
  this.innerHTML= "up";
}

  var cards=document.getElementsByClassName("card");
  for(var i=0;i<cards.length;i++){
     cards[i].addEventListener("click", clickHandler);
  }
<table id="card-container">
  <tbody>
    <tr>
      <td class="card">down</td>
      <td class="card">down</td>
    </tr>
    <tr>
      <td class="card">down</td>
      <td class="card">down</td>
    </tr>
  </tbody>
</table>

clickHandler function just loops through all the elements in the html with class name as "card" and sets it to down. And then later sets the value to the current one which was clicked, to up.

addEventListener js functions binds a function to an event.

var cards=document.getElementsByClassName("card");
for(var i=0;i<cards.length;i++){
    cards[i].addEventListener("click", clickHandler);
}

The above code just sets the click handler for all card elements.