jQuery Draggable containment visible window?
Asked Answered
A

3

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'
 });
Airman answered 19/2, 2012 at 17:43 Comment(0)
L
9

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

Example:

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

More info:

containment, scroll

Listen answered 6/1, 2016 at 11:4 Comment(2)
Note that you can also use a bounding box, so if you want to constrain say to 50 at the top but 35 at the bottom, then one can use: containment: [0, 50, 0, $(window).height() - 35].Pyrometallurgy
Thanks! This is what I am looking for.Khalil
W
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 });
Wheelchair answered 18/8, 2012 at 18:58 Comment(0)
N
0

try removing the greedy:true

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

Nita answered 12/11, 2017 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.