Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Draggable image when image is larger than the container

Making an image draggable does some pretty wacky things when the image is larger than the container... Does anyone know a way around this?

Here's my code...

<script type='text/javascript' src="scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="scripts/jquery-ui.js"></script>

<script type="text/javascript">

    $(document).ready(function() {

        $("img").draggable({ containment: "div", scroll: false });

    });

</script>

<style type="text/css">
    div {
        width:500px; 
        height:423px; 
        position:relative; 
        overflow:hidden;
    }
</style>

and...

<div>
    <img src="images/map.jpg" width="1000" height="845" alt="Map" />
</div>
like image 590
Tom Avatar asked Oct 25 '10 15:10

Tom


2 Answers

It is working if you set the the bounds manually:

$("img").draggable({ containment: [0, 0, 500, 423], scroll: false });
like image 158
krial Avatar answered Oct 10 '22 09:10

krial


I chose to set the containment dynamically based off the parent and child size by doing the following, JSFiddle Here:

$(function () {
    $("div[id='dragx']").draggable({
    drag : function(event,ui){
      var parent = ui.helper[0].parentNode;

      var dragWidth = ui.helper[0].clientWidth;
      var parentWidth = parent.clientWidth;
      var dragHeight = ui.helper[0].clientHeight;
      var parentHeight = parent.clientHeight;

      var widthDifference = dragWidth - parentWidth;
      var heightDifference = dragHeight - parentHeight;

      if(ui.position.left > 0) ui.position.left = 0;
      else if(ui.position.left < -widthDifference) ui.position.left = -widthDifference;

      if(ui.position.top > 0) ui.position.top = 0;
      else if(ui.position.top < -heightDifference) ui.position.top = -heightDifference;

      }
    });
});
like image 2
Arron Hyman Avatar answered Oct 10 '22 08:10

Arron Hyman