Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Draggable containment visible window?

I'm trying to contain my draggable element so it cannot be dragged outside of the viewable window, which works well if the user is at the top of the page, however if you scroll down at all then it messes it all up.

How can I do this?

$(".chat-wrapper > li.draggable").draggable({ 
 greedy: true, 
 handle: '.chat-button', 
 containment: 'html'
 });
like image 368
Dylan Cross Avatar asked Feb 19 '12 17:02

Dylan Cross


People also ask

What is containment for draggable?

The containment option is used to set that the draggable items will be contained in the specified container.

What is jQuery draggable?

jQuery UI draggable() method is used to make any DOM element draggable. Once the element is made draggable, you can move it by clicking on it with the mouse and drag it anywhere within the viewport.


2 Answers

Just use containment: 'window' and possible scroll: false

Example:

$('#selector').draggable({
    containment: 'window',
    scroll: false
});

More info:

containment, scroll

like image 69
mineroot Avatar answered Sep 18 '22 22:09

mineroot


$(".chat-wrapper > li.draggable")
.on('mousemove',function(){ // Update containment each time it's dragged
    $(this).draggable({
        greedy: true, 
        handle: '.chat-button',

        containment: // Set containment to current viewport
        [$(document).scrollLeft(),
        $(document).scrollTop(),
        $(document).scrollLeft()+$(window).width()-$(this).outerWidth(),
        $(document).scrollTop()+$(window).height()-$(this).outerHeight()]
    });
})
.draggable({ scroll: false });
like image 42
Gary Avatar answered Sep 17 '22 22:09

Gary