Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop jQuery draggable from scrolling off screen

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
}
like image 829
DasBeasto Avatar asked Jul 08 '15 02:07

DasBeasto


Video Answer


1 Answers

Please use this code :

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

DEMO

like image 60
Rino Raj Avatar answered Sep 30 '22 15:09

Rino Raj