How to prevent page scrolling while dragging an item?

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

My draggable div:

$("#stayaway").draggable() 

I did a search on the Internet and found this line of code. It was supposed to prevent scrolling.

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

All he does is fade the scroll bar, but you can still drag the div from the window size.

+5
source share
2 answers

Use the containment parameter:

 $("#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> 
+5
source

Use Containment !!

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

Selector: The drag and drop element will be contained in the bounding box of the first element found by the selector. If the item is not found, no containment will be set.

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

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

+5
source

All Articles