How to limit Draggable area in jQuery UI

jQuery UI is a great plugin that is built upon the popular jQuery JavaScript library. Using jQuery UI, we can easily create a draggable element for the web page.

Just like creating a draggable element, we can also limit the draggable area in jQuery UI. You may think that how it can be done. Well, don’t worry. Because here I am going to let you know, how you can set the limit to the draggable area.

Setting a limit to a draggable area is as easy as creating a draggable element. Well, I hope you can remember how we can create a simple draggable element just by using the draggable method of the jQuery UI. This method can take some options.

The containment option of jQuery UI

There is an option we can set to the draggable method to limit the area of dragging the element within a parent element. To do this, we just have to set the element as the value of that option.

The option for the draggable() method I am talking about is the containment where you can pass the ID, tag name or class as option value to limit the area of dragging within that parent element.

Actually, the containment option just specifies the region where we can drag our element.

Set limit to a draggable area with containment option

Now here I am going to show you what you are waiting for. Before I give you an example, let’s see how we can set the limit to the area of dragging our element below:

      containment: "PARENT_ELEMENT"

So simple. Isn’t it… We just have to set the element inside which our element can be dragged.

Practical example

Now see a practical example that you can follow. It will help you to understand exactly how you can limit your jQuery UI draggable area within a parent div.

Also, read:

Below is the HTML code:

<div id="draggableArea">
    <div id="draggable"><p>Drag Me</p></div> 

In the above HTML code, we have an element that we want to drag and also a parent element inside which the element can be only draggable.

Now, see the CSS code below:

#draggableArea {
    width: 750px;
    height: 500px;
    border: solid 1px #000;

#draggable { 
  width: 70px; 
  height: 70px; 
  background-color: #5cbbe0; 
  border-radius: 50%;
  cursor: move;

In our above CSS code, we have set the height and width of the parent element to set the draggable area. We also set some CSS to our draggable element.

Now see the jQuery code below that will do our main task:

$(function() { 
    containment: "#draggableArea"

That’s it. We did it. Now we can run our code on browser and we are able to see that a limit has been specified. Outside the parent element, we can’t drag our element. So we have successfully able to limit the draggable area within our parent element with jQuery UI.

One response to “How to limit Draggable area in jQuery UI”

  1. foysal says:

    thats cool

Leave a Reply

Your email address will not be published. Required fields are marked *