Restrict drag only in one direction

Uttara picture Uttara · Mar 25, 2013 · Viewed 15.9k times · Source

Using jQuery Draggable

How to restrict a draggable to be dragged only in one direction ?
i.e either only top or only bottom when axis: 'y'
and either only left or only right when axis: 'x'

This means that if I want a draggable (with axis set to 'y') to be dragged only to bottom, then it should not be able to drag it to top i.e it should remain in its place when tried to drag towards top

This is what I have tried but not working, i.e draggable is still getting dragged in upward direction

$('. draggable').draggable({
    axis: 'y',
    handle: '.top'
    drag: function( event, ui ) {
       var distance = ui.originalPosition.top - ui.position.top;

       // if dragged towards top
       if (distance > 0) { 
           //then set it to its initial state
           $('.draggable').css({top: ui.originalPosition.top + 'px'});
       }
   }
});

Answer

Uttara picture Uttara · May 14, 2013

Answering my own question (other alternative in addition to above answer) so as to help others

Taking a specific case say allow dragging only downwards when axis:'y'

<div class="draggable">draggable only downwards</div>

css

.draggable {
    position:absolute;
    top:0px;
    background:pink;
    height:100px;
    width:100%;
    left: 0px;
    text-align:center;
}

script

$('.draggable').draggable({
    axis: "y"
});    

$('.draggable').on('mousedown', function() {
    var x1 = x2 = $(".draggable").position().left;
    var y1 = $(".draggable").position().top;
    var y2 = ($(window).height() + $(".draggable").position().top);
    $(".draggable").draggable('option', 'containment', [x1, y1, x2, y2]);
});

Demo Link