Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

$("#stayaway").draggable()

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.

like image 421
K.Yazoglu Avatar asked Aug 22 '16 13:08

K.Yazoglu


People also ask

How do I stop web pages from scrolling?

To hide the horizontal scrollbar and prevent horizontal scrolling, use overflow-x: hidden: HTML. CSS.


2 Answers

Use the containment option:

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

Demo

$("#stayaway").draggable({containment: "window"})
#stayaway {
  width: 200px;
  height: 200px;
  background-color: silver;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<div id="stayaway"></div>
like image 200
Michał Perłakowski Avatar answered Oct 07 '22 13:10

Michał Perłakowski


Use Containment!!

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

Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.

Check out this fiddle (you can change it to a 500 x 500 square)

http://jsfiddle.net/Kpt2K/11/

like image 5
Muntasir Alam Avatar answered Oct 07 '22 14:10

Muntasir Alam