• Top Members
    Reps
    Posts
  • 834 Replies
    2585 Replies
  • 716 Replies
    2026 Replies
  • 331 Replies
    1928 Replies

JQuery Drag and Drop Script

User avatar
mikethedj4
VIP - Site Partner
Posts: 2593

JQuery Drag and Drop Script

Wed Mar 19, 2014 5:03 am

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;
});
Image

Post Reply

Return to “Tutorials”