I have a page whereby in order to create a new resizable/draggble div
the user clicks anywhere on a canvas and it appears next to where the click event occurred.
Once the new element has appeared the user can then resize or drag it around.
A better user experience would be to allow the user to mousedown, drag the new div
to the desired size and then mouseup to finish creation. E.g.
What I want
Which is like how drawing a rectangle works on this website: https://awwapp.com/
What I have
You'll see that my code just appends the new div
when dragging was detected. The user then has to go back and resize.
I haven't found much in general when researching using jQuery to detect dragging, apart from this but even this example is very much click OR drag when I require click AND drag.
My code, condensed for brevity is currently:
function newPlaceholderPosition(posX, posY, X, Y) {
cssTop = (Y - posY);
cssLeft = (X - posX);
var styles = [
"top: "+ Math.round(cssTop / 10) * 10 +"px;",
"left: "+ Math.round(cssLeft / 10) * 10 +"px;"
].join(' ');
return styles.toString();
}
function makePlaceholdersFunctional(elements) {
elements.resizable({
containment: "parent",
handles: 'ne, se, sw, nw',
minWidth: 100,
minHeight: 40,
autoHide: true,
});
elements.draggable({
containment: "parent",
drag: function() {
$("body").addClass("element-moving");
},
stop: function() {
$("body").removeClass("element-moving");
}
});
}
var isDragging = false;
$(".canvas")
.mousedown(function(e) {
isDragging = false;
// Log where the click took place
clickLocation = newPlaceholderPosition($(this).offset().left, $(this).offset().top, e.pageX, e.pageY);
})
.mousemove(function(e) {
// If the user is not dragging an existing div
if(!$('.canvas').hasClass("child-active")) {
isDragging = true;
}
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
// console.log("You weren't dragging on the canvas")
} else {
// console.log("You WERE dragging on the canvas")
$(".canvas").append('<div class="resizable" data-id="' + parseInt( $(".resizable").length + 1) + '" style="'+ clickLocation +'"></div>');
makePlaceholdersFunctional($(".resizable:last"));
}
});
Is something like this possible using jQuery UI? Could someone provide an example?