How to create a Simple Draggable Object without JQueryUI

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
January 27, 2016

Draggable objects are one of the most commonly seen elements on modern web applications these days. From adding Widgets in WordPress to moving cards around in Trello, a day doesn’t go by for many people without some drag-drop actions through multiple dashboard areas. If you are working on any web application or interface and need to add a draggable widget or content boxes, you can use JQuery plugins like JQueryUI, ZinoUI and other UI plugins for JQuery. But if its just a simple draggable object that you want to create without adding any extra plugins, you can do so easily in a few lines of code and just by using JQuery. Here’s a quick tutorial on how to add a draggable object using JQuery(without JQueryUI).

Lets get down to creating a simple HTML page where the draggable element will reside.

Its very simple, all we did here is create div called drag which will be our draggable element and applied some styling to it to make it conspicuous. Remember to replace the links to the JQuery file and the script file(which we will be creating in the next step) in the above code.

Now lets create a script.js file. Basically, the idea is to get trigger the div object with the id drag to move when the mouse key is pressed down. For this, we will be using JQuery’s mousedown event.

So, when the mouse is pressed down on the div with the id drag, we want it to take the HTML position of the mouse. This is done by setting its CSS properties, top and left the same as the mouse’s X and Y co-ordinate values at any point on the screen. We want the object to take the mouse’s co-ordinates only as long as the mouse is clicked down. As soon as the mouse is released, we want the object to stop moving. To do this, we add another event mouseup to the main document(because mousemove() was added to the document to track the mouse co-ordinates on mousedown() event. We want to unbind this from the document upon mouse’s release).

How to create a draggable element(using Jquery) that goes back to its original position upon mouse release

Now if you want the object to go back to its original position when the mouse is released, you can simply add a line of code and it would the trick for you. In that case, the code would look something like this(look for comment on the line added)

What we did here is simply removed the left and top from the style attribute we had added to the drag div.  You can also use remove the style attribute from the element to achieve similar results. Here’s is the Fiddle.

That’s it! That is how you can create a draggable object using JQuery and a few lines of code.

You may also like...