Reputation: 4849
I have the following html structure:
HTML
<div id="outer">
<div id="inner">
<div id="bounds">
<div id="myimage">
</div>
</div>
</div>
</div>
CSS
#outer
{
border: solid 1px red;
padding: 50px 30px 50px 30px;
float: left;
}
#inner
{
width: 300px;
height: 300px;
border: solid 1px black;
overflow:hidden;
position:relative;
}
#myimage
{
background-image:url('http://upload.wikimedia.org/wikipedia/commons/9/9a/Sample_Floorplan.jpg');
background-position : 0,0;
background-repeat:no-repeat;
width: 648px; /*TODO : size will be dynamic*/
height: 438px; /*TODO : size will be dynamic*/
position:relative;
}
JS
$("#myimage").draggable(); //{ containment: "#bounds" }
//$("#bounds").width(); //? value
//$("#bounds").height(); //? value
//$("#bounds").css("left",""); //? value
//$("#bounds").height("top","");? value
A "inner" div which has a draggable child div with background-image
.
The inner div has overflow:hidden
. What i need is to restrict the drag of the image so
that the whole image can be scrolled but the image should never be dragged completely out of the "inner" div (some part of the image must always remain visible).
Thats why i added a bounds
div . How can i define the dimensions and position for the
bounds
div which enables me to restrict the movement of the image.
Such that i can write
$("#myimage").draggable({ containment: "#bounds" });
http://api.jqueryui.com/draggable/#option-containment
Upvotes: 0
Views: 1009
Reputation: 11646
You need to create a div with
left as -width of your image
top as -height of your image
width as width * 2 + width of view port(300)
height as height * 2 + height of view port(300)
html
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="outer">
<div id="inner">
<div id="bounds">
</div>
<div id="myimage">
<div>
</div>
</div>
</body>
</html>
css
#outer
{
border: solid 1px red;
padding: 50px 30px 50px 30px;
float: left;
}
#inner
{
width: 300px;
height: 300px;
border: solid 1px black;
overflow:hidden;
position:relative;
}
#myimage
{
background-image:url('http://upload.wikimedia.org/wikipedia/commons/9/9a/Sample_Floorplan.jpg');
background-position : 0,0;
background-repeat:no-repeat;
width: 648px;
height: 438px;
position:relative;
}
javascript
var imgwidth = "648";
var imgheight = "438";
$("#bounds").css({
position:"absolute",
left: -imgwidth + 10,
top:-imgheight + 10,
width: imgwidth * 2 + 300 - 20,
height:imgheight * 2 + 300 - 20,
}
);
$("#myimage").draggable({ containment: "#bounds" });
Checkout this bin
Upvotes: 1