Paul
Paul

Reputation: 283

Event delegation, use of event Target in Javascript

This is the html code:

<table id="bagua-table">
<tr>
  <th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
  <td class="nw"><strong>Northwest</strong>
    <br>Metal
    <br>Silver
    <br>Elders
  </td>
  <td class="n"><strong>North</strong>
    <br>Water
    <br>Blue
    <br>Change
  </td>
  <td class="ne"><strong>Northeast</strong>
    <br>Earth
    <br>Yellow
    <br>Direction
  </td>
</tr>
<tr>
  <td class="w"><strong>West</strong>
    <br>Metal
    <br>Gold
    <br>Youth
  </td>
  <td class="c"><strong>Center</strong>
    <br>All
    <br>Purple
    <br>Harmony
  </td>
  <td class="e"><strong>East</strong>
    <br>Wood
    <br>Blue
    <br>Future
  </td>
</tr>
<tr>
  <td class="sw"><strong>Southwest</strong>
    <br>Earth
    <br>Brown
    <br>Tranquility
  </td>
  <td class="s"><strong>South</strong>
    <br>Fire
    <br>Orange
    <br>Fame
  </td>
  <td class="se"><strong>Southeast</strong>
    <br>Wood
    <br>Green
    <br>Romance
  </td>
</tr>

The script is to make any selected cell highlight and if clicked again, remove the highlight, What's the use of the selectedTd variable and the line that contains target.parentnode, what do those two lines do?

This is the Javascript code:

let table = document.getElementById('bagua-table');

let selectedTd;

table.onclick = function(event) {
  let target = event.target;

  while (target != this) {
    if (target.tagName == 'TD') {
      highlight(target);
      return;
    }
    target = target.parentNode;
  }
}

function highlight(node) {
  if (selectedTd) {
    selectedTd.classList.remove('highlight');
  }
  selectedTd = node;
  selectedTd.classList.add('highlight');//
}

Upvotes: 0

Views: 53

Answers (1)

Andy
Andy

Reputation: 79

target.parentNode will get the parent node that the current node belongs to. The line is setting the target to be the HTML element which holds the current element.

E.g. <div class="parent"><button class="child" /></div>. If target was the button, then the parent node would be the div.

This is happening every loop until a td element is found, or it reaches the global object.

selectedTd is used to keep a state of what the currently selected cell is. Every time the highlight function is called, it'll check if there is a selectedTd that already exists. The existing one will have its highlight class removed and will be replaced by the node passed into the function. This node will have the highlight class added.

Upvotes: 1

Related Questions