Created
February 5, 2025 06:40
-
-
Save RamGoel/7aad34fa58d8b739d123ff58e1e42ac0 to your computer and use it in GitHub Desktop.
Select and Auto-Unselect Grid (Interview Question)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const root = document.getElementById("root"); | |
const TwoDArray = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
]; | |
let selectedIds = []; | |
const onCardClick = (ev, container) => { | |
const target = ev.currentTarget; | |
const targetId = target.id; | |
// if already selected, unselect | |
if (selectedIds.includes(targetId)) { | |
selectedIds = selectedIds.filter((item) => item !== targetId); | |
target.classList.remove("grid-item-selected"); | |
} else { | |
selectedIds.push(targetId); | |
target.classList.add("grid-item-selected"); | |
console.log(selectedIds); | |
// check if selected all cards | |
if (selectedIds.length === container.childNodes.length) { | |
let idx = 0; | |
let ivId = setInterval(() => { | |
let box = document.getElementById(selectedIds[idx]); | |
box.classList.remove("grid-item-selected"); | |
if (idx === selectedIds.length - 1) { | |
selectedIds = []; | |
clearInterval(ivId); | |
} | |
idx++; | |
}, 1000); | |
} | |
} | |
}; | |
function createGrid(_arr) { | |
let container = document.createElement("div"); | |
container.classList.add("grid-container"); | |
container.id = "grid-box"; | |
TwoDArray.forEach((item, index) => { | |
item.forEach((item2, index) => { | |
let gridItem = document.createElement("div"); | |
gridItem.classList.add("grid-item"); | |
gridItem.textContent = item2; | |
gridItem.id = `card-${item2}`; | |
container.appendChild(gridItem); | |
gridItem.addEventListener("click", (ev) => onCardClick(ev, container)); | |
}); | |
}); | |
root.appendChild(container); | |
} | |
createGrid(TwoDArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment