$(function() {
var gs = parseInt($("#gs").val()),
sq = parseInt($("#sq").val()),
cRows = $(".drag-zone").height() / gs,
cCols = $(".drag-zone").width() / gs;
function drawGridLines(r, c, b) {
/*
input: Rows Integer, Cols integer, Buffer Integer
output: null
Based on the number or Rows and Cols, draw gridlines with a single buffer space between.
*/
for (var i = 0; i < r; i++) {
$("<div>", {
class: "row"
}).css({
height: (b - 1) + "px",
width: "100%",
top: (b * i) + "px"
}).insertBefore($(".drag-zone"));
}
for (var i = 0; i < c; i++) {
$("<div>", {
class: "col"
}).css({
width: (b - 1) + "px",
height: "100%",
left: (b * i) + "px"
}).insertBefore($(".drag-zone"));
}
}
function makeSquare(s, tObj) {
/*
input: Size Integer, Target jQuery Object
output: null
Create a square div element with class 'item' and append it to the Target.
*/
$("<div>", {
class: "item"
}).css({
width: s + "px",
height: s + "px"
}).appendTo(tObj);
}
function makeDrag(obj, b) {
/*
input: jQuery Object, Buffer Integer
output: null
Initialize the jQuery Object with Draggable, using specific options for square Grid spacing
*/
obj.draggable({
containment: "parent",
grid: [b, b]
})
}
drawGridLines(cRows, cCols, gs);
makeSquare(sq, $(".drag-zone"));
makeDrag($(".item"), gs);
$("#go-btn").click(function() {
var ngs = parseInt($("#gs").val()),
nsq = parseInt($("#sq").val()),
rw = $(".drag-zone").height() / ngs,
cl = $(".drag-zone").width() / ngs;
$(".row, .col, .item").remove();
if (nsq < 2) {
nsq = 2;
}
drawGridLines(rw, cl, ngs);
makeSquare(nsq, $(".drag-zone"));
makeDrag($(".item"), ngs);
});
});
* {
margin: 0;
padding: 0;
}
body {
background: #ccc;
}
p input {
width: 40px;
}
.grid {
background: black;
position: relative;
width: 400px;
height: 300px;
}
.drag-zone {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: transparent;
}
.item {
background: red;
}
.row {
display: block;
position: absolute;
border-bottom: 1px solid #FFF;
left: 0;
}
.col {
display: block;
position: absolute;
border-right: 1px solid white;
top: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Gutter Size: <input id="gs" type="text" value="20" /> Square Size: <input id="sq" type="text" value="60" /> <button id="go-btn">Redraw</button>
<div class="grid">
<div class="drag-zone">
</div>
</div>