Draggable Element with JQuery (No jQuery UI)

Draggable feature in a webpage can bring a smooth user experience. If you want to enable draggable functionality to an element but without jQuery UI, here’s another jQuery snippet you can use. This snippet will make any DOM element draggable, which you can move around to different position on the viewport.

The element you add to the page, such as DIV, it will stay fixed, to make it draggable, just add ID attribute to it as shown below. The jQuery script will take care of the rest.

JQUERY
123456789101112131415161718

var draggable = $('#dragit'); //element 
draggable.on('mousedown', function(e){
	var dr = $(this).addClass("drag").css("cursor","move");
	height = dr.outerHeight();
	width = dr.outerWidth();
	ypos = dr.offset().top + height - e.pageY,
	xpos = dr.offset().left + width - e.pageX;
	$(document.body).on('mousemove', function(e){
		var itop = e.pageY + ypos - height;
		var ileft = e.pageX + xpos - width;
		if(dr.hasClass("drag")){
			dr.offset({top: itop,left: ileft});
		}
	}).on('mouseup', function(e){
			dr.removeClass("drag");
	});
});
HTML
123

<div id="dragit">Drag me</div>

What this jQuery script basically does here is, each time mouse is moved, it applies the mouse position values to element’s top and left CSS property, making it move towards the direction mouse is moving.

Constrain movement

The following jQuery code constraints the movement of draggable element, you need to wrap the object with an outer element, which becomes the draggable area for the element.

JQUERY
1234567891011121314151617181920212223242526

var draggable = $('#dragit-contained'); //element 
draggable.on('mousedown', function(e){
	var dr = $(this).addClass("drag").css("cursor","move");
	height = dr.outerHeight();
	width = dr.outerWidth();
	max_left = dr.parent().offset().left + dr.parent().width() - dr.width();
	max_top = dr.parent().offset().top + dr.parent().height() - dr.height();
	min_left = dr.parent().offset().left;
	min_top = dr.parent().offset().top;
	ypos = dr.offset().top + height - e.pageY,
	xpos = dr.offset().left + width - e.pageX;
	$(document.body).on('mousemove', function(e){
		var itop = e.pageY + ypos - height;
		var ileft = e.pageX + xpos - width;
		if(dr.hasClass("drag")){
			if(itop <= min_top ) { itop = min_top; }
			if(ileft <= min_left ) { ileft = min_left; }
			if(itop >= max_top ) { itop = max_top; }
			if(ileft >= max_left ) { ileft = max_left; }
			dr.offset({ top: itop,left: ileft});
		}
	}).on('mouseup', function(e){
			dr.removeClass("drag");
	});
});
HTML
12345

<div class="draggable-area">
<div id="dragit-contained">Drag me</div>
</div>