Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - draggable div with zoom

This is my code:

http://jsfiddle.net/652nk/

HTML

<div id="canvas">
    <div id="dragme"></div>
</div>

CSS

#canvas {
    width:500px;
    height:250px;
    border:1px solid #444;
    zoom:0.7;
}
#dragme {
    width:100px;
    height:50px;
    background:#f30;
}

JS

$(function(){
    $('#dragme').draggable({containment:'parent'})
})

I have a major issue when using css zoom property. Position of target draggable div is not coordinated with cursor position.

Is there any clean and simple solution? I should be able to change zoom dynamically.

like image 221
enloz Avatar asked Dec 22 '11 14:12

enloz


2 Answers

You don't need to set zoom property. I just added the difference to draggable's position which occurs due to the zoom property. Hope it helps.

Fiddle

http://jsfiddle.net/TqUeS/

JS

var zoom = $('#canvas').css('zoom');
var canvasHeight = $('#canvas').height();
var canvasWidth = $('#canvas').width();

$('#dragme').draggable({
    drag: function(evt,ui)
    {
        // zoom fix
        ui.position.top = Math.round(ui.position.top / zoom);
        ui.position.left = Math.round(ui.position.left / zoom);

        // don't let draggable get outside the canvas
        if (ui.position.left < 0) 
            ui.position.left = 0;
        if (ui.position.left + $(this).width() > canvasWidth)
            ui.position.left = canvasWidth - $(this).width();  
        if (ui.position.top < 0)
            ui.position.top = 0;
        if (ui.position.top + $(this).height() > canvasHeight)
            ui.position.top = canvasHeight - $(this).height();  

    }                 
});
like image 127
tuze Avatar answered Sep 27 '22 16:09

tuze


The solution above did not work out for me. So I found my own. I wanted to share it if someone else also has the same issue.

var zoom = $('#canvas').css('zoom');    
$('#dragme').draggable({
    drag: function(evt,ui)
    {
         var factor = (1 / zoom) - 1

         ui.position.top += Math.round((ui.position.top - ui.originalPosition.top) * factor)
         ui.position.left += Math.round((ui.position.left - ui.originalPosition.left) * factor)   
    }                 
});
like image 30
Yusuf Demirag Avatar answered Sep 27 '22 15:09

Yusuf Demirag