I have a div, and I have a draggable image inside of the div. $("#image").draggable();
How do I keep the image from leaving the div?
$("#image").draggable();
div{
width:200px;
height:200px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx- arrow-cursor.png"/>
</div>
You have to do this: containment: 'div',
Entire code:
$( init );
function init() {
$("#image").draggable({
containment: 'div',
});
};
div{
width:200px;
height:200px;
border: 1px solid black;
}
#image {
height: 50px;
width: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
</div>
This should solve your problem. I tried it.