Ad

Dragging Image Within A Boundary Using JQuery

- 1 answer

I am trying to make an image draggable in a boundary using jQuery but I can only drag it vertically. How can I freely drag it within a boundary?

$("#map").draggable({
  containment: 'parent'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">

<div id="parent" style="width: 800px; height: 700px">
  <div id="map" class="map">
    <img src="Images/map.PNG" style="width:500px; height:350px;">
  </div>
</div>

Ad

Answer

I can only drag it vertically.

That's because the div element is a block level element with a width of 100% of the parent element. Since the #map element has the same width as the #parent element, it can't be dragged vertically.

How can I freely drag it within a boundary?

If you want the #map element to have a width based on the child img element, just change the display of the element to inline-block so that it has a "shrink-to-fit" width.

Updated Example:

$("#map").draggable({
  containment: 'parent'
});
#parent {
  width: 800px;
  height: 700px;
  border: 1px solid;
}
#map {
  display: inline-block;
}
#map img {
  width: 500px;
  height: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">

<div id="parent">
  <div id="map" class="map">
    <img src="//placehold.it/100">
  </div>
</div>

Ad
source: stackoverflow.com
Ad