Search code examples
jquery-uidraggable

jquery ui draggable - how can I prevent dragging outside the top of my document?


I've set up a jquery draggable, which can be moved around the entire document, it's not contained by anything, and this is acceptable, as when the user drags, I want them to be able to drag as far down the page (or left or right) as they wish.

Indeed, the only restriction I want - is that they should be prevented dragging the element outside of the top of the page.

Is it possible to prevent dragging outside only one edge of a container?


Solution

  • You could overwrite the position of the element being dragged.

    This fiddle is an example of the position overwriting : http://jsbin.com/ufarif/7/edit

    Here is an example to not permit to be more close than 80 px of the left border

    $('[id^="drag-"]').each(function() {
        $(this).draggable({
            opacity: 0.7,
            cursorAt: { top: 15, left: 50 },        
            scroll: true,
            stop: function(){},  
            drag : function(e,ui){            
                //Do not permit to be more close than 80 px of the left border
                console.log(ui.position.left);      
                if(ui.position.left < 80)    
                    ui.position.left = 80;
            });
    });