Reputation: 10182
I am trying to extend the area that an element will snap to using jQuery UI's draggable feature. As of right now, I can get the element to snap to another element by using this basic code:
$('.drag').draggable({
containment: 'parent',
snap: true
});
The problem I am having is once I drag one element away from the other, I lose the snap functionality. Is there a way to extend the line that determines where to snap to?
For example, let's say we have 3 elements and I want to align all three elements on the same vertical axis. That axis will always be the left-hand side of any of the elements and move with them. Can I snap to the vertical axis of element #1 regardless of the vertical position of element #2 or #3?
[Element #1] | |
| | |
| | |
|<-- Snap to here regardless of "y" location
| | |
| | |
| [Element #2] |
| | |
| |<-- Or to here |
| | [Element #3]
| | |
| | |<-- Or to here
I tried adding top and bottom margins to each element to extend the line, but because of the added margins, I couldn't move the elements vertically within the parent container.
Here is a fiddle to better illustrate what I am trying to accomplish. http://jsfiddle.net/3KNSn/
Thank you!
Upvotes: 2
Views: 1791
Reputation: 4958
You can create a special drag-reference object to serve as your snap axis.
$(function() {
$('.drag').draggable({
stop: function (event, ui) {
// Remove any pre-existing drag references
$('.drag-reference').remove();
$('.drag').each(function (i, item) {
var $reference = $('<div>', { 'class': 'drag-reference' });
var $elem = $(item);
var $container = $elem.parent();
var position = $elem.position();
var left = position.left + 'px';
$reference.insertBefore($elem);
$reference.css({
top: 0,
left: left,
height: $container.height()
});
});
},
containment: 'parent',
snap: '.drag-reference, .drag'
});
});
I have a red border on the .drag-reference objects just to show you how they work, but if you remove that border you should have the behavior you want with no visible artifacts to give away your trick.
Upvotes: 5