Pat
Pat

Reputation: 15

Jquery draggable - get image coordinates

I have a div containing an image that can be dragged around inside the div to get the coordinates for the cropping of the image. I was able to get the right coordinates but as soon as I dragged the image to a certain position I cannot redrag to another position, if I don't like the detail of the image... where do I go wrong... The final positions x + y will be saved into a hidden input... here's my code:

    <!-- Div container 350x350px with border where detail of image can be chosen -->
<div id="draggable">
    <!-- Image (bigger than div draggable) that is draggable in the div -->
<img id="dragimg" src="<?php echo $path_to_image_directory.$filename; ?>" />
</div>


<script type="text/javascript">
    $(document).ready(function() {
        $("#dragimg").draggable({
            stop: function(){
                var finalxPos = $(this).css('left');
                var finalyPos = $(this).css('top');
                //  alert( "Drag stopped!\n\nOffset: (" 
                + finalxPos + ", " + 
                finalyPos + ")\n");
                $('#crop [name="finalX"]').val(finalxPos);
                $('#crop [name="finalY"]').val(finalyPos);
            }
        });
    });
</script>

Can you aid me in solving my issue?

Upvotes: 0

Views: 1995

Answers (1)

Mike Boutin
Mike Boutin

Reputation: 5347

To get the absolute position in his parent is the .position()

$('.object').bind('drag',function(){

 var obj = $(this);
 var position = obj.position();
 var leftpos = position.left;
 var toppos = position.top;
 });

and you can add a input val function like

<input type="text" name="top" id="topVal"/>

and in the bind function

$('#topVal').val(toppos);

Upvotes: 1

Related Questions