JQuery Drag and Drop Script

1 post Page 1 of 1
Contributors
User avatar
mikethedj4
VIP - Site Partner
VIP - Site Partner
Posts: 2592
Joined: Thu Mar 25, 2010 4:36 am

JQuery Drag and Drop Script
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;
});
1 post Page 1 of 1
Return to “Tutorials”