Understanding event delegation and utilizing event targets in JavaScript

This is the HTML code snippet:

<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>

In the script provided, when a cell in the table is clicked, it will be highlighted. If clicked again, the highlight will be removed. The selectedTd variable and the line containing target.parentNode play important roles in this functionality.

Here is the JavaScript code segment:

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');
}

Answer №1

target.parentNode retrieves the parent node of the current element. This line assigns the variable target to the HTML element containing the current element.

For example, in the code

<div class="parent"><button class="child" /></div>
, if target is the button, then the parent node would be the div.

This process repeats until a td element is located or it reaches the global object.

selectedTd maintains the state of the currently selected cell. Whenever the highlight function is invoked, it checks for an existing selectedTd. The existing one has its highlight class removed and replaced by the new node parameter passed into the function. This new node will have the highlight class added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The AWS API Gateway quickly times out when utilizing child_process within Lambda functions

I'm encountering an issue with my Lambda function being called through API Gateway. Whenever the Lambda triggers a spawn call on a child_process object, the API Gateway immediately returns a 504 timeout error. Despite having set the API gateway timeou ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Creating custom Bootstrap Card Groups by dynamically generating the specified number of cards with Angular directives

I am currently using Angular 9.1.8 for my project. For my Angular component, I have implemented Bootstrap Card Groups and Cards to display a large result set of cards in rows with more than two cards per row. Below are four example cards: <div class=&q ...

What is the best way to renew an access token with axios?

I have been struggling to understand the concept of refreshing tokens after reading numerous articles on the topic. They all seem too convoluted for me to grasp. Could someone please simplify it for me? Here is an overview of what I am trying to achieve: ...

Tips for mapping through an array received from props

My current task involves mapping an array passed into the component via props. To provide some context, I have a ViewPosts page where I call the Comments component by passing the post as a prop. The objective is to extract the array from the props and map ...

JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service. So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well. Here is a snippet of the array: [ ...

Trouble with showing data retrieved from MongoDB

Currently, I'm diving into the world of MongoDB by developing a basic app that should simply showcase items from a database. Initially, I managed to make it work with my MongoShell; however, now I'm aiming to utilize the MongoDB Cluster instead. ...

What is the memory layout of untyped JavaScript arrays, given their lack of homogeneity?

I am interested in learning more about the performance attributes of untyped JavaScript arrays, given that they are not homogenous. I wonder how this is handled internally. For instance, if I were to have a number and an arbitrary object in an array, woul ...

Only one tab can be open at a time, and when clicking on another tab, the focus will shift to that tab

My main concern is opening one tab at a time. The issue lies in the fact that when a tab is open and another tab is clicked, the height of the first tab reduces and the section tab title moves to the top of the screen making it invisible to the user. I wan ...

Maximizing the performance of the Three.js WebGLRenderer

My Three.js application sometimes requires a complete re-render without reloading the page. I've tried reusing the WebGLRenderer variable to avoid memory leaks, but they still occur. To maintain performance and prevent the multiplication of WebGL con ...

What is the best way to center a fixed position background image within a container that is slightly shifted from the top of the viewport?

How can I center a background-image vertically, which has a fixed background-attachment and is positioned 100px from the top? The background-size property is set to cover for horizontal centering but the vertical alignment is off. Below is the HTML code: ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

require a global function that accesses a variable inside it

I am currently struggling with a piece of JavaScript code that is causing some difficulty for me. The code is located inside a function, and I am trying to access the soft_left and soft_top variable in other functions without much success. Below is the rel ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

The AngularJS function invoked itself within the structure

When working with my form, I encountered a problem involving custom input directives and text fields. In addition to these elements, there are buttons: one for adding a new input to the form which is linked to the function $scope.AddNewItem() in the contro ...

Extract information from an external website using AJAX in Laravel

On my cart page, I utilize ajax to retrieve destination information from the user and provide them with shipping options to calculate their shipping cost. While everything is functioning properly, one issue remains: I am unsure of how to iterate through t ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

Error: Reference 'ref' is undefined in the 'no-undef' context. I am interested in experimenting with loading images from Firebase storage

While working with React, I encountered an issue when trying to fetch an image URL from Firebase Storage and display the image. The error 'ref' is not defined (no-undef) occurred. https://firebase.google.com/docs/storage/web/create-reference Th ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...

Create a separate server session specifically for handling an ajax request?

Currently, I am working with a collection of PHP server-side scripts that manage user session state by utilizing PHP sessions extensively for authenticated users. For the client side within a mobile application and using Jquery ajax, I am striving to esta ...