JSFiddle - React, Tailwind, and code Playground
by crisply
HTML
<div class="canvas">
<div class="draggable" id="Point0">Point0</div>
</div>
<div id="results">coordination</div>
<input type='button' id="btn_add" value='Add box' />
<input type='button' id="btn_getCoord" value="Get Coornination" />
<input type='button' id="btn_erase" value='Erase All' />
CSS
.draggable {
position: absolute;
top: 0;
left: 0;
width: 10px;
height: 10px;
background: green;
cursor: move;
}
.canvas {
width: 500px;
height: 400px;
background: #ccc;
position: relative;
margin: 2em auto;
}
#results {
text-align: center;
}
JavaScript
var index=1;
$(".draggable").draggable({
containment: "parent",
});
$('#btn_add').click(function () {
var pointID = "Point"+(index++);
var top = Math.floor(Math.random() * 501);
var left = Math.floor(Math.random() * 401);
drawPoint(pointID, top, left);
});
$('#btn_getCoord').click(function () {
writeCoordination();
});
$('#btn_erase').click(function () {
eraseAllPoint();
writeCoordination();
});
function drawPoint(pointId, top, left) {
var htmlData = $('<div class="draggable" id=' + pointId + '>' + pointId + '</div>');
htmlData.css({ 'left': top + 'px', 'top': left + 'px' });
$('.canvas').append(htmlData);
$(".draggable").draggable({ containment: "parent" });
}
function writeCoordination() {
var output = '-Coordination-';
$('.draggable').each(function () {
output += '<br />' + $(this).attr("id") + ' => x: ' + $(this).position().left + ', y: ' + $(this).position().top;
});
$('#results').html(output);
}
function eraseAllPoint() {
$('.canvas').html('');
}