I'm trying to build a jQuery plugin that allows you to drag and draw a rectangle (or a div with a border) but I'm not sure how to do it. I don't know of any that currently have this ability so I don't know where to look for an example of how to do this.
How can I implement drag and draw in jQuery?
To add drag-and-drop functionality to your pages, you need to include both the jQuery library and the jQuery UI plugin. jQuery UI is a fantastic plugin for jQuery that adds all sorts of useful user interface widgets, effects and behaviours — including drag-and-drop.
Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port. If the value of this option is set to false, it will prevent the DOM elements to be dragged .
jQueryUI provides draggable() method to make any DOM element draggable. Once the element is draggable, you can move that element by clicking on it with the mouse and dragging it anywhere within the viewport.
The basics for something like this are quite simple, when you think about it:
mousedown
events on some container (possible the entire document);
event
object (e.pageX
and e.pageY
);mousemove
events to change the width
and height
object (based on the mouse coordinates);mouseup
event to detach the mousemove
event listener.The aforementioned absolute placed element is, e.g., a <div>
with a border and background: transparent
.
Update: here is an example:
$(function() {
var $container = $('#container');
var $selection = $('<div>').addClass('selection-box');
$container.on('mousedown', function(e) {
var click_y = e.pageY;
var click_x = e.pageX;
$selection.css({
'top': click_y,
'left': click_x,
'width': 0,
'height': 0
});
$selection.appendTo($container);
$container.on('mousemove', function(e) {
var move_x = e.pageX,
move_y = e.pageY,
width = Math.abs(move_x - click_x),
height = Math.abs(move_y - click_y),
new_x, new_y;
new_x = (move_x < click_x) ? (click_x - width) : click_x;
new_y = (move_y < click_y) ? (click_y - height) : click_y;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).on('mouseup', function(e) {
$container.off('mousemove');
$selection.remove();
});
});
});
Demo: http://jsbin.com/ireqix/226/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With