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:

Drag Me

356 views
Jquery

Comments

2 Responses to “How to create drag and drop effect using JQuery.”

Leave Comment

(required)

(required)