i'm trying to make a chess board and i'm stuck with moving the pieces. my function 'moving_pieces' not working as expected and i don't know why. here is the function.
function moving_pieces() {
//getting pieces ids
let images = document.querySelectorAll('img');
let target_piece = null;
images.forEach(img => {
img.addEventListener('click', function handle_move () {
target_piece = img;
console.log(img) //for debugging
});
});
//getting squares ids
let squares = document.querySelectorAll('.square');
let target_square = null;
squares.forEach(square => {
square.addEventListener('click', function handle_id() {
if (!square.firstChild) {
target_square = square;
console.log(square) //for debugging
}
});
});
target_square.appendChild(target_piece);
}
for future readers.
EDIT: i edited my variable scopes and now it's fine but the pieces still not moving.
EDIT 2: i found the problem. i have to put the target_square.appendChild(target_piece); inside of squares.forEach
and it work just fine, happy coding :)
what i'm trying to do is to get the piece id and square id and then append the piece in that square. i succeeded in getting the ids but the piece is not moving.
Looks like you are declaring the target_square and target_piece inside the loops. Try moving the declaration outside the loops. Like this:
function moving_pieces() {
//getting pieces ids
let images = document.querySelectorAll('img');
let target_piece = null;
images.forEach(img => {
img.addEventListener('click', function handle_move () {
target_piece = img;
console.log(img.parentElement) //for debugging
});
});
//getting squares ids
let squares = document.querySelectorAll('.square');
let target_square = null;
squares.forEach(square => {
square.addEventListener('click', function handle_id() {
if (!square.firstChild) {
target_square = square;
console.log(square) //for debugging
}
});
});
target_square.appendChild(target_piece);
}
I created a far from perfect example on how to move an element to a new square. In my case it's just an 'X' and the code is far from complete for what you need but it might give you some insights :)