Limit the Draggable area using jQuery UI

← PrevNext →

You can use jQuery UI plug-in to enable draggable functionality to an element. You can drag the element anywhere on a webpage. In-addition you can create Movable and Resizable elements on your web page using the plug-in. See this example. Here in this post I’ll show you how you can limit the draggable area using jQuery UI.

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.

The Markup and the Script

Add the jQuery CDN’s inside the <head> tag.

<!DOCTYPE html>

<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>

#intro {
  display: block;
  padding: 5px;
  width: 120px; 
  height: 120px;
  border:solid 1px #FF7F27;

    <div id='parentContainer'>
        <div id='intro'>You can drag this element anywhere on the page.</div>

    $(document).ready(function () {
Try it

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.

    $(document).ready(function () {
            containment: 'parent'
Try it

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.

    $(document).ready(function () {
            containment: '#parentContainer'

So, instead of using the parent keyword, I have assigned the id of the parent element.

Also, 👉 try this example.

That's it. Thanks for reading 🙂.

← PreviousNext →