Brandon Leung Brandon Leung - 3 months ago 16
Javascript Question

JavaScript Click Handlers - How to solve without jQuery?

So recently I was given a JavaScript assessment for a job and was asked this question. I'd like to know how to properly solve it with vanilla JS. Code 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.

Comments