I'm trying to build a very basic chess board (with no embedded rules) as a learning challenge. Basically my board is made of 64 divs, where each div has a class .square
. I have two functions: one for adding the .active
class to the clicked square, and another function for moving the piece with the .active
class to the new square. I've tried to put the two different eventListeners to call the different functions in an IF ELSE statement, but my condition doesn't work because the querySelector doesn't check in real time if there's any div with the class .active
at that given moment.
My code looks like this:
let squares = document.querySelectorAll(`.square`);
let activeSquares = document.querySelectorAll(`.active`);
// This condition needs to check if there's any square with the class .active in REAL TIME
if (activeSquares.length > 0) {
squares.forEach(square => {
square.addEventListener(`click`, movePiece);
function movePiece() {
let pieceToMove = document.querySelector(`.active`).textContent;
square.textContent = pieceToMove;
}
});
} else {
squares.forEach(square => {
square.addEventListener(`click`, selectPiece);
function selectPiece() {
square.className = `active square`;
}
});
}
How do I make it check for the class in real time? Or is my approach completely wrong? Please be merciful, I've only been learning this stuff for a couple months, if I'm missing some basic knowledge please point it out so I can look it up.
Thanks!