Draggable (and Resizable) <div> using jQuery
Resources for a tutorial by Benedict Lewis.
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<button id="btn">Zoom in</button>
<div id="wrapper" style="background-color:aliceblue;padding:50px;">
<div id="innerWrapper" style="background-color: ivory; min-height: 200px; width: 400px; ">
<div id="draggable" style="background-color:burlywood;max-width:100px;">Move me</div>
</div>
</div>
CSS
#wrapper {
width: 100%;
height: 300px;
overflow: auto;
background-color: black;
}
#innerWrapper {
background-color: grey;
width: 250px;
height: 250px;
position: relative;
-webkit-transform-origin: 0 0;
-moz-transform-origin: 0 0;
transform-origin: 0 0;
-ms-transform-origin: 0 0;
}
#draggable {
background-color: red;
display: inline;
position: absolute;
top: 10px;
left: 10px;
}
JavaScript
const draggableElement = $("#draggable")
let containmentArea = $("#innerWrapper");
let percent = 1
draggableElement.draggable({
cursor: "move",
drag: dragFix,
});
function dragFix(event, ui) {
var contWidth = containmentArea.width(),
contHeight = containmentArea.height();
ui.position.left = Math.max(0, Math.min(ui.position.left / percent, contWidth - ui.helper.width()));
ui.position.top = Math.max(0, Math.min(ui.position.top / percent, contHeight - ui.helper.height()));
}
function setScale(scalePercentage) {
percent = scalePercentage;
$("#innerWrapper").css({
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
})
}
const btn = document.getElementById("btn");
btn.addEventListener("click", function() {
setScale(1.2)
});