Page 1 of 1

JQuery Drag and Drop Script

Posted: Wed Mar 19, 2014 4:03 am
by mikethedj4
See it in action - http://jsfiddle.net/q8ghc/

I decided to learn how to do this without the need for a plugin so enjoy!

JQuery:
Code: Select all
var onmove = false;
var x1;var y1;var x2;var y2;var x3; var y3;

$('.rect').on('mousedown touchstart', function(e) {
    onmove = 1;
    x1 = event.clientX;
    y1 = event.clientY;
    x3 = parseInt($('.rect').css('left'));
    y3 = parseInt($('.rect').css('top'));
});

$(document).on('mousemove touchmove', function(e) {
    if (onmove) {
        x2 = e.clientX;
        y2 = e.clientY;
         distX = x2 - x1;
         distY = y2 - y1;
         var newX = x3 + distX;
         var newY = y3 + distY;
         $('.rect').css('left', newX);
         $('.rect').css('top', newY);
    }
}).on('mouseup touchend', function() {
    onmove = false;
});