Draggable elements with Javascript

making a div draggable with plain javascript. here is what we make:

click and drag

First, we give the div that we can drag in an Id, and also a class for the div that is being dragged. and we also added a onmousedown attribute to call the drag start function

<div id = "drag-container" onmousedown="dragStart(this)"> <div class = "draggable"> click and drag</div> </div>

now are can add the dragStart function.

//declare the drag container variable var dragContainer; function dragStart(element) { //get the container and the element dragContainer = document.getElementById('drag-container'); draggedElement = element; //set the position if it wasn't defined before if (draggedElement.style.left == '') draggedElement.style.left = '20px'; if (draggedElement.style.top == '') draggedElement.style.top = '20px'; //get the position of the div xOffset = event.pageX - parseInt(draggedElement.style.left); yOffset = event.pageY - parseInt(draggedElement.style.top); //addEventListeners for when the mouse moves and when the mouse is up dragContainer.addEventListener('mousemove', drag); dragContainer.addEventListener('mouseup', endDrag); }

the dragStart function gets called with the user begins to drag. we are just using this function to get the current location of the div, and also add the other event listeners.

and this is the drag function:

function drag(e) { //changing the div's position every time the mouse moves draggedElement.style.left = e.pageX - xOffset + 'px' draggedElement.style.top = e.pageY - yOffset + 'px' }

this one is pretty simple, just updating the div's position. there is one more function left.

function endDrag() { dragContainer.removeEventListener('mousemove', drag); dragContainer.removeEventListener('mouseup', endDrag); }

and that's it!

the reason that I added the event listeners on the container and not is div itself is because the mousemove event listener only works if you are over the element, and if move your cursor too fast, the drag stops working.