Master Drag-and-Drop in JavaScript: Three Ways to Build a Reusable Drag Object
This article walks you through three approaches to implement drag-and-drop in JavaScript—plain code, a native object wrapper, and a jQuery extension—covering essential concepts like transform compatibility, event handling, position calculations, and object-oriented encapsulation, with detailed code examples and visual diagrams.
In previous articles I shared basic JavaScript knowledge; now we move to a practical exercise: using the concepts covered earlier to encapsulate a draggable object. To illustrate different techniques, three implementations are presented.
1. Direct implementation without encapsulation
We manipulate a DOM element’s top, left or translate to change its position. Each button click moves the element 5 px.
Modifying top / left triggers a page repaint, while translate does not; therefore translate is preferred for performance.
2. Native JavaScript drag object
CSS3 transform requires vendor‑specific prefixes. The supported property can be detected with the following method:
If the detection returns an empty string, the browser does not support transform, and we fall back to left / top.
3. Getting the element’s initial position
Different browsers expose computed styles differently, especially IE. A cross‑browser function is needed:
Using this function we can retrieve the element’s initial coordinates:
4. Updating the element’s position during drag
Each time the mouse moves we set a new position for the target element:
5. Required events
On desktop browsers the trio mousedown, mousemove, mouseup enables dragging. mousedown – triggered when the mouse button is pressed. mousemove – triggered while the mouse moves with the button held down. mouseup – triggered when the button is released.
On mobile devices the equivalents are touchstart , touchmove , touchend .
The event object passed to callbacks provides precise cursor coordinates, which are essential for calculating movement.
6. Dragging principle
When the drag starts we record the initial mouse position and the element’s initial position. During movement we compute the displacement (dis) and apply it:
dis = currentMousePos - initialMousePos
newElementPos = dis + initialElementPosThis calculation is performed on every mousemove event, and the element is repositioned accordingly. On mouseup we perform cleanup (see code).
7. Mind‑map for implementation steps
A visual mind‑map outlines the entire drag‑and‑drop workflow, helping beginners organize logic before coding.
8. Code implementation
part1 – Preparation
part2 – Utility functions
(Code omitted for brevity; see original source.)
part3 – Event callbacks
The three callbacks implement the core drag logic as described in the mind‑map.
9. Encapsulating the drag object
Using the object‑oriented concepts from earlier chapters, we wrap the drag logic into a reusable constructor. The code resides in its own file and is executed inside an IIFE to avoid polluting the global scope.
In a plain concatenated bundle a leading semicolon prevents errors when previous modules omit a terminating semicolon.
Properties and methods can be placed in the constructor, prototype, or module scope, each with distinct characteristics:
Constructor: each instance gets its own copy of the property/method.
Prototype: shared across all instances, saving memory.
Module scope: private to the module, inaccessible to instances.
Choosing the right location depends on whether a property should be instance‑specific, shared, or private.
10. Final remarks
The drag object is now fully encapsulated. Readers are encouraged to apply the same mindset to other components such as modals or carousels, reinforcing object‑oriented skills that remain valuable across future projects.
JavaScript source code
Feel free to experiment with this pattern and extend it to other UI components.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
