6

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'
 });
Dylan Cross
  • 5,918
  • 22
  • 77
  • 118

3 Answers3

9

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

Example:

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

More info:

containment, scroll

mineroot
  • 1,607
  • 16
  • 23
2
$(".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 });
Gary
  • 13,303
  • 18
  • 49
  • 71
0

try removing the greedy:true

I tried to achieve the exact same thing and removing it worked