Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery draggable - multiple snap (to) objects with different snapMode for each object

Situation as follows - one draggable div, can snap to multiple other divs. What I need to achieve - specify different snap modes for different divs. For example - snap:'#firstDiv', snapMode:'inner' and for that same draggable div another snap:'#secondDiv', snapMode:'outer'

HTML:

<div class="wrapper">
    <div id="first" class="tile"><p>first</p></div>
    <div id="second" class="tile"><p>second</p></div>
    <div id="third"><p>3</p></div>
</div>

CSS:

.wrapper { 
    width:100%; 
    height:400px; 
    position:relative; 
}
#first, #second, #third { 
    position:absolute; 
    width:100px; 
    height:100px; 
    border:1px solid #000; 
    text-align:center;
}
#first { top:10px; left:10px; }
#second { right:100px; bottom:100px; }

#third {
    width:50px;
    height:50px;
    left:50px;
    top:150px;
}
p { margin:10px; padding:0px; font-weight:bold; }

JS, with basic snap to something:

$(document).ready(function(){
    $( "#third").draggable({
        containment: '.wrapper',
        cursor: 'move',
        snap: '.tile',
        snapMode: 'outer'
    });     
});

Here is jsFiddle with above code: http://jsfiddle.net/563UZ/1/

like image 235
Kashins DaWeeD Avatar asked Aug 01 '26 10:08

Kashins DaWeeD


1 Answers

I have also been trying to get this sort of functionality out of jQuery UI's snapMode. Here is a work-around that sort of does the trick:

You can change the draggable's snapMode for a particular div by turning it into a droppable. When the draggable is dragged over the droppable, you change it's snapMode option from outer to inner, and then when it's dragged out (and the droppable is no longer active), you change it back.

Here are my edits to your fiddle:
http://jsfiddle.net/coffeeCola/563UZ/31/
http://jsfiddle.net/coffeeCola/563UZ/43/

Unfortunately, when the droppable is set to tolerance: 'touch' the whole thing sort of wigs out. Setting it to tolerance: pointer creates the desired behavior, but the draggable will still snap to the outside of the div before the options are changed.
[Update]
I was able to remove the unwanted behavior described above by turning the droppable into the parent of the element and added a margin/padding that is slightly larger than the draggables snapTolerance.

like image 195
coffeecola Avatar answered Aug 04 '26 01:08

coffeecola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!