This code implements a draggable div element in HTML, CSS, and JavaScript. The div element with the class "js-is-draggable"
can be moved around the screen by clicking and dragging. The major functionality involves handling mouse or touch events to track the div’s position and update it accordingly.
This feature is helpful for creating interactive user interfaces where draggable elements enhance the user experience by allowing them to rearrange elements on the page easily.
How to Create Draggable Div Element in HTML CSS & JavaScript
1. First, in the <head>
section of your HTML file, include the Normalize.css CDN link to ensure a consistent styling base: (Optional)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
2. Create a div element with the class “card” and “js-is-draggable”. This will be the element you can drag around:
<div class="card positioned js-is-draggable" aria-grabbed="false">Drag Me 🎉</div>
3. Now, customize the appearance of your draggable div in the CSS section. The following code includes styles for a visually appealing and responsive draggable card:
:root { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; font-size: 16px; } .card { display: flex; justify-content: center; align-items: center; width: 20rem; height: 10rem; background-color: #efefef; border-radius: .625rem; box-shadow: 0 .0625rem .1875rem rgba(51, 51, 51, .12), 0 .0625rem .125rem rgba(51, 51, 51, .12); transition: box-shadow 75ms linear; } .positioned { position: relative; top: 25%; left: 25%; } .card:hover { cursor: move; } .card.js-is-dragging { box-shadow: 0 .4375rem .875rem rgba(51, 51, 51, .25), 0 .3125rem .3125rem rgba(51, 51, 51, .22); } .js-is-draggable { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
4. In the final step, copy the following JavaScript code to enable the dragging functionality. This code includes functions to handle mouse and touch events, updating the div’s position accordingly:
let mover; let offsets; let position; function addEvent(type, callback, target = document) {target.addEventListener(type, callback, false);} function removeEvent(type, callback, target = document) {target.removeEventListener(type, callback);} function offsetPosition(target) { let node = target; let X = 0; let Y = 0; do { X += node.offsetLeft; Y += node.offsetTop; node = node.offsetParent; } while ( node); return { X, Y }; } function parentsUntilMatch(target, filter) { if (!target || target.nodeType === 9) return null; switch (true) { case 'matchesSelector' in target: if (target.matchesSelector(filter)) return target; break; case 'mozMatchesSelector' in target: if (target.mozMatchesSelector(filter)) return target; break; case 'msMatchesSelector' in target: if (target.msMatchesSelector(filter)) return target; break; case 'oMatchesSelector' in target: if (target.oMatchesSelector(filter)) return target; break; case 'webkitMatchesSelector' in target: if (target.webkitMatchesSelector(filter)) return target; break; default: if (target.matches(filter)) return target; break;} return parentsUntilMatch(target.parentNode, filter); } function styleStringFromObj(obj) { let str = ''; for (const prop in obj) { str += `${prop}:${obj[prop]};`; } return str; } function mousedown(isTouch = false) { const MOVE = isTouch ? 'touchmove' : 'mousemove'; const END = isTouch ? 'touchend' : 'mouseup'; return function caller(evt) { const target = parentsUntilMatch(evt.target, '.js-is-draggable'); if (!target) return; mover = target; offsets = { X: evt.pageX, Y: evt.pageY }; position = offsetPosition(mover); mover.setAttribute('style', styleStringFromObj({ position: 'relative', top: `${position.Y}px`, left: `${position.X}px` })); mover.classList.add('js-is-dragging'); mover.setAttribute('aria-grabbed', true); addEvent(MOVE, mousemove); addEvent(END, mouseup(isTouch)); }; } function mousemove(evt) { // evt.preventDefault(); // new offsets based on mouse position const newOffsets = { X: evt.pageX, Y: evt.pageY }; const newY = position.Y + (newOffsets.Y - offsets.Y); const newX = position.X + (newOffsets.X - offsets.X); // update styles mover.style.top = newY + 'px'; mover.style.left = newX + 'px'; // update object offsets = newOffsets; // update position position = { X: newX, Y: newY }; } function mouseup(isTouch = false) { const MOVE = isTouch ? 'touchmove' : 'mousemove'; const END = isTouch ? 'touchend' : 'mouseup'; return function caller(evt) { removeEvent(MOVE, mousemove); removeEvent(END, caller); mover.classList.remove('js-is-dragging'); mover.setAttribute('aria-grabbed', false); mover = offsets = position = undefined; }; } addEvent('mousedown', mousedown()); addEvent('touchstart', mousedown(true));
Feel free to customize the card’s size, appearance, and additional styles to match your website’s design
That’s all! hopefully, you have successfully created a draggable div element on your website. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.