JSFiddle - React, Tailwind, and code Playground
HTML
<div id="selection"></div>
<div class="selectable">A</div>
<div class="selectable">B</div>
<div class="selectable">C</div>
<div class="selectable">D</div>
<div class="selectable">E</div>
CSS
#selection {
display: none;
position: absolute;
background: lightblue;
border-color: blue;
border-width: 1px;
border-style: solid;
opacity: .5;
}
* {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.selectable {
font-size: 7em;
background-color: lightgreen;
display: inline-block;
width: 100px;
margin: 10px;
text-align: center;
}
JavaScript
var indexOf = function(needle) {
if(typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
if(this[i] === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
(function() {
var beginX, beginY, active;
var selection = document.getElementById("selection");
var selecteds = [];
window.onmousedown = function (e) {
beginX = e.clientX;
beginY = e.clientY;
active = true;
selection.style.display = "block";
window.onmousemove(e);
selecteds = [];
};
window.onmousemove = function (e) {
if (active) {
var x = Math.min(beginX, e.clientX);
var y = Math.min(beginY, e.clientY);
var w = Math.abs(beginX - e.clientX);
var h = Math.abs(beginY - e.clientY);
selection.style.left = x+"px";
selection.style.top = y+"px";
selection.style.width = w+"px";
selection.style.height = h+"px";
var list = document.getElementsByClassName("selectable");
for (var i = 0; i < list.length; ++i) {
var rect = list[i].getBoundingClientRect();
if (rect.bottom > y && rect.top < y+h &&
rect.right > x && rect.left < x+w) {
list[i].style.backgroundColor = "red";
selecteds.push(list[i]);
}
else {
list[i].style.backgroundColor = "lightgreen";
}
}
}
};
window.onmouseup = function (e) {
active = false;
selection.style.display = "none";
var list = document.getElementsByClassName("selectable");
for...