Let’s see how we can make an element draggable.
I have a <div> element on my webpage. Usually an HTML DOM element is static. I can make it draggable, so I can drag the element and change its location anywhere on my web page.
Add the jQuery CDN’s inside the <head> tag.
<!DOCTYPE html> <html> <head> <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <style> #intro { display: block; padding: 5px; width: 120px; height: 120px; border:solid 1px #FF7F27; } </style> </head> <body> <div id='parentContainer'> <div id='intro'>You can drag this element anywhere on the page.</div> </div> </body> <script> $(document).ready(function () { $('#intro').draggable({}); }); </script> </html>
Click the Try it 👆 button to check the result. You will see that the element can be dragged (and dropped) anywhere on the web page. If there are other elements on the web page, it will overlap the elements.
Limit draggable area using ‘containment’ option
We can restrict the draggable area. It is simple. All you have to do is, add an option called containment to the draggable() method.
<script> $(document).ready(function () { $('#intro').draggable({ containment: 'parent' }); }); </script>
The containment option has a value parent. Now, the draggable area of the child <div> element (<div id='intro'>) is restricted or limited to the element’s parent area (width and height), which is another <div> element (<div id='mainContainer'>).
You can also do this.
<script> $(document).ready(function () { $('#intro').draggable({ containment: '#parentContainer' }); }); </script>
So, instead of using the parent keyword, I have assigned the id of the parent element.
Also, 👉 try this example.