Stop jQuery draggable from scrolling off screen

DasBeasto picture DasBeasto · Jul 8, 2015 · Viewed 9.1k times · Source

When using jQuery UI draggable on a div element you can drag the element "off" the right side of the page, but the page will simply extend and autoscroll with the element. This is problematic as I am trying to initiate an event when the element reaches the right side of the window. One caveat is that I can't simply bound the div so that it cant leave because I want the dragging to stop when your cursor meets the edge not the div (try dragging it off the left side to see what I mean, I simply want to replicate that on the right).

What I've tried:

body{ overflow: hidden;} - at first glance works, but if you inspect close the body is actually scrolling just not with a visible scrollbar. Plus this is to be used in a plugin so I cant limit users to only overflow: hidden bodys.

Creating wrapper div of window size/fixed position to trigger events but the body still extends out just under the fixed div.

I just need a way to say if I'm dragging an element, dont scroll the window over.

Here is a jsFiddle that allows dragging but goes off the window: http://jsfiddle.net/9dx1cxu8/

html:
<div class="box"></div>

javascript (jQueryUi):
$('.box').draggable();

css:
.box{
  left:200px;
  top:200px;
  width: 150px;
  height: 150px;
  box-shadow: inset 0 0 20px
}

Answer

Rino Raj picture Rino Raj · Jul 8, 2015

Please use this code :

$( ".box" ).draggable({ containment: "#containment-wrapper", scroll: false })

DEMO