How to create drag and drop effect using JQuery.
There is no any drag and drop event defined in javascript but it can be obtained using other events . We can find various drag and drop plugins which can be easily integrated and used but I noticed that most of the javascript programmer are unaware of how drag and drop effect is created using other events. Here I go through simple techniques of how drag and drop is created using other events. First , lets create one simple box which we want to be dragged and dropped. Css for the Div Box
#box{ width:80px; height:80px; background-color:#9DCF5A; border:1px solid #3F8E2B; cursor:move; position:absolute; }
This will create one box with height and width 80px with green background. Lets go through the steps of making the above box dragable. Three different mouse events that will be used to acquire the result are mousedown, mousemove, mouseup . Here goes the javascript and jquery code.
$(document).ready( function () { var _mousedown = false; var _prevMouseMoveX = 0; var _prevMouseMoveY = 0; var _div = $('#box'); var pLeft = 0; var pTop = 0; $( _div ).mousedown(function(e) { _prevMouseMoveX = e.clientX; _prevMouseMoveY = e.clientY; var _pos = $(this).position(); pLeft = _pos.left; pTop = _pos.top; _mousedown = true; }); $(document).mousemove(function(e) { if ( _mousedown != undefined ) { $(_div).css({ 'top' : pTop + (e.clientY - _prevMouseMoveY), 'left' : pLeft + (e.clientX - _prevMouseMoveX) }); } }); $( _div ).mouseup(function() { _mousedown = false; }); });
Demo:


Hi I am big fan of JQuery…..and this is wonderful snippet….but I have got a little problem here …the box can be dragged outside the gray region and cannot be moved in again…
well the snippet I had provided is only about how the drag and drop effect is rendered in the browser using other mouse events. If u want it to be not dragged outside the grey box then u should add some more codes on mouse move event by calculating the width, height , left position , and top position of its parent div form which u dont want the moving box get out of.