JSFiddle - React, Tailwind, and code Playground
CSS
.grid {
margin: 0px auto auto;
border: 1px solid #000;
border-width: 0 1px 1px 0;
background-color: #CCC;
position: relative;
}
.grid div {
border: 1px solid #000;
border-width: 1px 0 0 1px;
float: left;
}
#selectionBox {
position: absolute;
z-index: 3;
display: none;
background-color: red;
width: 10px;
height: 10px;
}
JavaScript
function creategrid(size){
var standardW = Math.floor((500) / size),
standardH = Math.floor((500) / size);
var standard = document.createElement('div');
standard.id = 'grid';
standard.className = 'grid';
standard.style.width = (standardW * size) + 'px';
standard.style.height = (standardH * size) + 'px';
for (var i = 0; i < standardH; i++) {
for (var p = 0; p < standardW; p++) {
var cell = document.createElement('div');
cell.style.height = (size - 1) + 'px';
cell.style.width = (size - 1) + 'px';
cell.style.position = 'relative'
cell.style.zIndex= '2';
standard.appendChild(cell);
}
}
document.body.appendChild(standard);
}
var isDragging = false,
dragStart,
cellSpacing = 10,
gridOffset,
selectionBox;
function getMousePos (e) {
return {
'left': Math.floor((e.pageX - gridOffset.left) / cellSpacing) * cellSpacing,
'top': Math.floor((e.pageY - gridOffset.top) / cellSpacing) * cellSpacing
};
}
$(document).ready(function(){
creategrid(10);
gridOffset = $('#grid').offset();
selectionBox = $('<div>').attr({id: 'selectionBox'})
.appendTo($('#grid'));
$('#grid').on('mousedown', function(e){
isDragging = true;
var pos = getMousePos(e);
dragStart = pos;
selectionBox.css({
left: pos.left,
top: pos.top,
width: 10,
height: 10
}).show();
});
$('#grid').on('mouseup', function(e){
isDragging = false;
});
$('#grid').on('mousemove', function(e){
if(!isDragging)
return false;
var pos = getMousePos(e);
var diff = {
'left': pos.left - dragStart.left,
'top': pos.top - dragStart.top
};
if(diff.left > 0 && diff.top > 0){
selectionBox.css({
...