Skip to content

Instantly share code, notes, and snippets.

@nmajor
Created June 10, 2020 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmajor/2cd66a9e4d74496e18d3af42d0cc54c7 to your computer and use it in GitHub Desktop.
Save nmajor/2cd66a9e4d74496e18d3af42d0cc54c7 to your computer and use it in GitHub Desktop.
const start = () => {
// 1. DONE - Event listener on click
// select td elements
// 3. DONE - Add class "empty" to clicked element
// 2. DONE - Find the previously empty element (class="empty")
// 4. DONE - Add the number from the clicked element to
// the previously empty element
// 5. DONE - Remove the number from the cicked element.
// 6. DONE - Remove the class "empty" from the previously
// empty element
// 7. Some elements are not supposed to be clickable
square.foreach(() =>{})
const squares = document.querySelectorAll("td");
squares.forEach((square) => {
square.addEventListener("click", (evt) => {
// Renaming for clarity
const clickedSquare = square;
const emptySquare = document.querySelector(".empty");
const clickedCol = clickedSquare.cellIndex;
const clickedRow = clickedSquare.parentElement.rowIndex;
const emptyCol = emptySquare.cellIndex;
const emptyRow = emptySquare.parentElement.rowIndex;
if ((clickedCol === emptyCol && clickedRow === emptyRow + 1) ||
(clickedCol === emptyCol && clickedRow === emptyRow - 1) ||
(clickedRow === emptyRow && clickedCol === emptyCol + 1) ||
(clickedRow === emptyRow && clickedCol === emptyCol - 1)) {
// Get the number from inside the clicked square
const clickedNumber = clickedSquare.innerText;
// Use query selector to find the current empty square
clickedSquare.classList.add("empty");
emptySquare.classList.remove("empty");
clickedSquare.innerHTML = '';
emptySquare.textContent += clickedNumber;
}
});
});
}
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment