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