The wijsuperpanel widget allows us to add elements to it and replace the browsers scrollbars with it's own scrollbars. You can read more about the wijsuperpanel here. Wouldn't it be good if we could drag and drop elements from and to the wijsuperpanel. In this article I'm going to explain how to do just that using jQueryUI's draggable and droppable functionalities.
Making elements draggable and droppable
First of all, lets add some div elements to the wijsuperpanel.
Div 1
Div 2
Div 3
Div 4
Div 5
Div 6
Div 7
To enable draggability or droppability of the div elements, we just need to set the elements as draggable and the container as droppable in the following way:
$(".elements div").draggable();
$(".element").droppable();
We're going to drag elements from the wijsuperpanel to the document and from the document to wijsuperpanel, hence we need to define the object where the elements would be dragged. We do this by using the containment option and setting its value to 'document'. We can define whether the element itself should be dragged or a clone by using the helper option.
$(".elements div").draggable({
containment: "document",
helper: 'clone'
});
Drag and Drop
The drag and drop functionality is pretty easy to implement. To be able to drop the 'div' element in the relevant container, we need to handle the drop event. In this event we check if the position where the element is being dropped is acceptable or not. If it is, we can append the element to the relevant container otherwise we can cancel the event. The ui.draggable gives us the current element being dragged.
$(".elements").droppable({
revert: 'valid',
greedy: true,
hoverClass: "dropHover",
tolerance: 'pointer',
drop: function (event, ui) {
if (ui.position.left >= left && ui.position.left <= outerwidth && ui.position.top >= top && ui.position.top <= outerheight) {
if (ui.draggable.parents(".elements").length == 0) {
ui.draggable.insertAfter($(".elements").children()[$(".elements").children().length - 1]);
ui.draggable.css('top', ui.position.top);
ui.draggable.css('left', ui.position.left);
ui.draggable.draggable('destroy').draggable(); /* need to reset the draggability */
}
}
else {
event.preventDefault();
}
}
});
$("body").droppable({
revert: 'valid',
tolerance: 'pointer',
hoverClass: "dropHover",
drop: function (event, ui) {
if ((ui.position.left < left || ui.position.left > outerwidth) || (ui.position.top < top || ui.position.top > outerheight)) {
$(this).append(ui.draggable);
ui.draggable.css('top', ui.position.top);
ui.draggable.css('left', ui.position.left);
ui.draggable.css('position', 'absolute');
ui.draggable.draggable('destroy').draggable({
containment: 'document',
helper: 'clone'
});
} /* need to reset the draggability */
else {
event.preventDefault();
}
}
});
Conclusion
I'm sure this drag and drop functionality would be helpful in many ways. You can always modify it as per your requirements. You can download the given sample for complete implementation. Download Sample