Restricting the draggable area in jQuery UI

12,971

You can do this by wrapping the image in a container div that's twice as large as the image, minus the widnow div size, and offset by the size of the range div. That and the containment option and you should be all set.

jsFiddle example

HTML

<div id="range">
    <div id="container">
        <img src="http://www.hdwallpapers.in/walls/enchanted_forest-wide.jpg" id="map" />
    </div>
</div>

JS

jQuery("#map").draggable({
    containment: $('#container')
});

CSS

#range {
    width:400px;
    height:400px;
    overflow:hidden;
    border:1px solid black;
    position:relative;
}
#container {
    position:absolute;
    top:-800px;
    left:-1520px;
    width: 3440px;
    height: 2000px;
}
#map {
    width: 1920px;
    height: 1200px;
    top:800px;
    left:1520px;
}

The image below should give you an idea as to the size of the container relative to the image and the viewport. The viewport is the smaller square in the middle of the image with a black border and the wrapper is the larger overall rectangle. You can see the image as being moved to the extreme positions.

enter image description here

Share:
12,971
Gautam Krishnan
Author by

Gautam Krishnan

UI/UX/Visual/Product Designer.

Updated on June 07, 2022

Comments

  • Gautam Krishnan
    Gautam Krishnan almost 2 years

    I am trying to create a draggable area within a div. It works fine but I do not want the white space outside the draggable area and hence want to limit the area that can be dragged. What I have come up so far is here in this fiddle.

    The image is initially positioned to the top-left of the parent div. If you drag it to the right or bottom, you can see the white space, which I wouldn't prefer. How can I restrict this?

    I think that it can be done using the Containment parameter in Draggable event of jQuery UI using

    $( ".selector" ).draggable({ containment: "" });
    

    But I am not able to figure out how. Also, if the whole page was a single draggable element (something similar to Google Maps), how can I limit that?