Ways to detect events even after the object has been swapped out in JavaScript

I am currently developing a JavaScript-based Scrabble game and encountering a puzzling issue. The problem arises when tiles are generated within a tile rack div using a specific function, and an event listener is set up to respond to clicks on the tile divs. After clicking on a section of the board followed by a tile div, the tile should be placed on the board and then removed from its parent div (the tile rack). This process involves creating an array containing the tile divs, and upon removing a div from this array, the parent div is updated with the new array. While this mechanism functions correctly, it encounters a complication where the event listener ceases to work after the old tiles replace the new ones in the parent div.

Below is a snippet of my code along with a link to the full code for further clarification:

let bag = ["A|1", ... /* long list continues */];

// Function to populate player's plate or stick with tiles
function fillStick(player, numberOfTilesNeeded, playerplate, id) {
  // Logic here...
}

fillStick(player1, 7, player1plate, "tile");
fillStick(player2, 7, player2plate, "rile");

function removeTile(player, playerplate, id) {
  // Logic to remove tile...
}

// Event listener for placing tiles on the board
let tileClicked = 0;
let allTiles = document.querySelectorAll(".tile");

allTiles.forEach((e) => {
  e.addEventListener("click", () => {
    // Mouse click logic...
  });
});

To delve deeper into the issue and explore the complete code, please visit: https://codepen.io/crentsil/pen/WNpeoKo

Answer №1

In my opinion, a better approach to solving this problem would be to rethink how you handle event listeners for each tile. Rather than attaching a listener to every single tile element, consider adding a single listener to the overall container of the tiles. This way, when an inner tile is clicked, the event will "bubble" up through the DOM tree. Once it reaches the container div, you can capture the event and identify the originally clicked tile by using the event.target property.

Markup:

<div id="board">
  <div id="1"> 1 </div>
  <div id="2"> 2 </div>
  <div id="3"> 3 </div>
</div>

CSS:

#board > div {
  width: 50px;
  height: 50px;
  background-color: gray;
  margin: 10px;
}

JavaScript:

document.getElementById('board').addEventListener('click', (e) => {
  let target = e.target;
  alert(`${target.id} was clicked`);
})

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 presence of double quotes in stringified JSON is undesired

I am currently working on a weather forecasting website where the API returns pure JSON data. However, when I convert this data to a string and add it to an element in order to display it on the webpage, I encounter a problem with double quotes appearing. ...

Transforming brand logos through hover on image maps

Despite finding numerous posts addressing this issue, I am still encountering problems with my code: <div id="product_tabs_description_tabbed_contents" style="display: block;"><img style="margin-left: -10px; opacity: 1 !important;" src="{{media u ...

Tips for maintaining the cleanliness of PHP-generated HTML output in the 'View Source' option

I've been noticing a problem today while examining the source code on a website. I typically use PHP output in my templates to generate dynamic content. Initially, the templates are written in HTML only, with clean indentation and formatting. The PHP ...

Creating a WebExtension using Angular and TypeScript

I am currently working on creating a WebExtension using Angular and Ionic. The extension successfully loads the application and enables communication between Content Script and Background Script. However, I am facing an issue where the TypeScript code is n ...

What is the best way to retrieve an <a> tag element using Selenium in Python?

I am fairly new to using Selenium and could use some guidance with the following issue. I am attempting to create a birthday bot for Facebook, but navigating through the platform's latest UI has been challenging with JavaScript disabled. I've bee ...

Tips for effectively validating with ParsleyJS remote validator?

I've been trying to solve a problem for hours now, but I can't seem to figure out how to retrieve a value in php and pass it back to js. Here is the input field in question: <input type="text" class="form-control input-lg" name="nr_ref" id=" ...

Leveraging the power of HTML5 alongside Angularjs and Node/Express within the MEAN.js boilerplate framework

I've decided to kickstart my app using the mean.js () boilerplate because of its built-in authentication/authorization features. However, I've hit a roadblock when it comes to incorporating HTML5 into my project. In my Angular app, I've en ...

What is the best way to send the $_SESSION['var'] array to jquery and initiate an ajax request?

I'm dealing with an issue here. I need to retrieve all the items within the $_SESSION['cart'] array and pass it to jQuery so that it can be used in a php-ajax file. My question is, how can this be accomplished? This is what I have in mind: ...

data being returned twice onpopstate

After experimenting with onpopstate, I encountered an issue. When I click the back button in my browser, the URL changes as expected, but the page code loads twice, resulting in duplicate lists and div elements. Why is this happening and how can it be reso ...

What could be causing this issue with my Mongoose.js program when it freezes during a 'nested' save operation?

[edit]: I made a revision to the previous question, providing a very precise reproducible example. This is the program I've created. I have developed two Schemas named ASchema and BSchema with collections A and B respectively. Then, I generated ...

Angularjs directives failing to compute accurately~

I'm working with an AngularJS directive where the HTML template is compiled within the linker function. var htmlTemplate = '<img ng-src="~/img/logos/{{account.Logo}}" width="45" height="35" />' var linker = function (scope, element) ...

Managing errors through middleware functions

Currently, I've been studying node.js on and off. I came across this question: Middleware 1: app.use(function(req, res, next) { db.load(function(err, session) { if (err) { return next(err); } ... }); }); Middleware 2: app.u ...

Execute npm build in sbt for play framework

Exploring sbt/play configuration is a new challenge for me. Working with play 2.3.8 to host my javascript application, my project utilizes: .enablePlugins(SbtWeb) .enablePlugins(play.PlayScala) .settings( ... libraryDependencies ++= WebDependancies :+ ...

Center 3 elements horizontally using Flexbox, ensuring the center element is aligned properly

Is it possible to center 3 elements using flexbox on a page? The middle element should be centered on the page, while the left and right elements can vary in width. Please refer to the image below: https://i.sstatic.net/IVdz8.png I am not certain if this ...

Utilize a specific component to enclose particular words within a contenteditable div in an Angular project

I have a task at hand where I need to manipulate text input from a contenteditable division, use regex to identify specific words, and then wrap those words within an angular component. Although I have managed to successfully replace the text with the com ...

Retrieve the index of a v-for loop and then send it as a parameter to a specific function

When working with a select element generated by a v-for loop in Vue, it is important to be able to retrieve the index of the selected option. This way, you can use that index in a function for further processing. However, I have been struggling to achieve ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...