view raw
K.Yazoglu K.Yazoglu - 9 months ago 32
CSS Question

How to prevent the page from scrolling when dragging an element?

I have a draggable div. I want it to be only draggable within the size of my screen. But now anyone can drag it and make it go out of the boundaries.

My draggable div:


I made a search on the web and found this line of code. It was suppose to prevent scrolling.

$("body").css("overflow", "hidden")

All it does is to disappear scroll bar but you can drag the div out of the window size anyway.


Use the containment option:

$("#stayaway").draggable({containment: "window"})


$("#stayaway").draggable({containment: "window"})
#stayaway {
  width: 200px;
  height: 200px;
  background-color: silver;
  text-align: center;
<script src=""></script>
<script src=""></script>
<div id="stayaway"></div>