My goal was to create a selection of divs that could be clicked and then manipulated collectively by moving the mouse over them.
Starting with just one div for testing, I encountered an issue when clicking and moving the mouse too quickly. The cursor changed to no-drop, and the function wouldn't execute unless I clicked again.
Below is the code snippet:
boxes = document.querySelectorAll('.box');
let itemList = [];
let selectedList = [];
//I created selectedList to allow for multiple selections in the future.
for (let box of boxes) {
itemList.push(box);
box.addEventListener("mousedown", mousedown);
};
//Each box listens for mousedown events and is added to itemList.
function mousedown(e) {
item = e.target;
deselectAll(); //Deselect all divs if one is clicked
item.selected = true; //Select the clicked div
selectedListUpdate();
window.addEventListener('mousemove', mousemove);
function mousemove(e) {
for (let item of selectedList) {
item.style.background = getRandomColor();
//This function changes the background color of all selected items as the mouse moves.
//In the future, this will be updated to allow for dragging functionality.
};
};
window.addEventListener('mouseup', mouseup);
function mouseup(e) {
window.removeEventListener('mouseup', mouseup);
window.removeEventListener('mousemove', mousemove);
}; //Stopping the effects of mouse movement after releasing the click while keeping items selected
};
function selectedListUpdate() {
selectedList = itemList.filter(x => x.selected == true);
for (let x of selectedList) {
x.style.outline = "white solid 2px";
};
unselectedList = itemList.filter(x => x.selected == false)
for (let x of unselectedList) {
x.style.outline = "0";
};
}; //Outline every item in selectedList
function deselectAll(e) {
for (x of itemList) {
x.selected = false;
};
selectedList = [];
}; //Reset selectedList
function getRandomColor() {
let r = Math.floor((Math.random() * 155) + 100);
let g = Math.floor((Math.random() * 155) + 100);
let b = Math.floor((Math.random() * 155) + 100);
return `rgb(${r} ${g} ${b})`;
}; //Example of function executed while mouse is moving
body {
margin: 0px;
background: #333;
}
.box {
margin: 10px;
background: white;
width: 100px;
height: 100px;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</body>
</html>