jQuery drag to select, constrained to elements, rather than typical drag box
drag-and-drop, jquery
Solution
After the previous failed attempt I've now come up with a working solution. It would appear that jQuery UI selectable is not suitable, as it uses that rectangular selection, so I've had to roll my own.
In the example below (see jsFiddle for full code), the selectable elements are `a.date`. These elements should have `position: relative` set.
Firstly, I append a child element with class `.drag-proxy`. This is positioned absolutely, and covers the same area as the child. It's got no content so it sits transparently above.
These proxy elements are made draggable and droppable.
When the element is dragged and dropped onto another element, it is moved back to its starting point (so that subsequent selections work).
Then we cycle through all the proxy elements, indentifying the elements in the selection range, and then setting a class on the parent `a.date` element.
$(function() {
$('a.date').each(function() {
$(this).append('<a href="' + $(this).attr('href') + '" class="drag-proxy" id="proxy_' + $(this).attr('id') + '"></a>');
});
var $currentlyDragged;
$('.drag-proxy').draggable({
start: function() {
$currentlyDragged = $(this);
},
// Once drag has finished, return the drag-proxy to its original position
stop: function() {
$(this).css('top', 0).css('left', 0);
$currentlyDragged = null;
}
});
$('.drag-proxy').droppable({
over: function(e, ui) {
var from_id = $currentlyDragged.attr('id');
var to_id = $(this).attr('id');
$('.date').removeClass('selected');
var started = selecting = false;
$('.drag-proxy').each(function() {
var $this = $(this);
var this_id = $this.attr('id');
if (started === false && (this_id == from_id || this_id == to_id)) {
selecting = true;
}
if (selecting) {
$this.parent().addClass('selected');
if (started === true && (this_id == from_id || this_id == to_id)) {
selecting = false;
}
}
if (started === false && (this_id == from_id || this_id == to_id)) {
started = true;
}
});
},
drop: function(e, ui) {
// do whatever you need to do once selection ends
}
});
});
See the jsFiddle for the full example.
Problem
I want to use a drag to select feature, but rather than select a square area on screen, and select anything within that square, I want to select any element between my initial choice and the one I release the click on. This is best explained visually. I do not want to do this: Instead I want to do this: