Success! I was able to solve the issue by making adjustments when the mouse enters or leaves the tile.
let isMouseDown: boolean = false;
let startNodeClicked: boolean = false;
let targetNodeClicked: boolean = false;
document.addEventListener("mousedown", () => {
isMouseDown = true;
});
document.addEventListener("mouseup", () => {
isMouseDown = false;
});
export const handleEvents = () => {
for (let i = 0; i < 16; i++) {
for (let j = 0; j < 45; j++) {
const node: Node = board[i][j];
const nodeElement: HTMLElement = board[i][j].DOMElement;
nodeElement.addEventListener("mouseleave", () => {
removeStartNodeOnDrag(node, nodeElement);
});
nodeElement.addEventListener("mouseenter", () => {
addStartNodeOnDrag(node, nodeElement);
});
nodeElement.addEventListener("mouseleave", () => {
removeTargetNodeOnDrag(node, nodeElement);
});
nodeElement.addEventListener("mouseenter", () => {
addTargetNodeOnDrag(node, nodeElement);
});
}
}
};
const removeStartNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
if (node.type === "start" && isMouseDown) {
nodeElement.classList.remove("start");
node.type = "empty";
node.state = "unvisited";
startNodeClicked = true;
}
};
const addStartNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
if (node.type === "empty" && isMouseDown && startNodeClicked) {
nodeElement.classList.add("start");
node.type = "start";
node.state = "visited";
startNodeClicked = false;
}
};
const removeTargetNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
if (node.type === "target" && isMouseDown) {
nodeElement.classList.remove("target");
node.type = "empty";
targetNodeClicked = true;
}
};
const addTargetNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
if (node.type === "empty" && isMouseDown && targetNodeClicked) {
nodeElement.classList.add("target");
node.type = "target";
targetNodeClicked = false;
}
};