var dragAndDrop = document.createElement('div'); dragAndDrop.innerHTML = 'Drag and Drop'; dragAndDrop.style.width = '100px'; dragAndDrop.style.height = '100px'; dragAndDrop.style.backgroundColor = 'red'; dragAndDrop.style.position = 'absolute'; dragAndDrop.style.top = '0px'; dragAndDrop.style.left = '0px'; dragAndDrop.style.cursor = 'pointer'; dragAndDrop.style.zIndex = '9999'; document.body.appendChild(dragAndDrop); var mouseX = 0; var mouseY = 0; var offsetX = 0; var offsetY = 0; var isDown = false; dragAndDrop.addEventListener('mousedown', function(e) { isDown = true; offsetX = dragAndDrop.offsetLeft - e.clientX; offsetY = dragAndDrop.offsetTop - e.clientY; }); document.addEventListener('mouseup', function() { isDown = false; }); document.addEventListener('mousemove', function(e) { mouseX = e.clientX; mouseY = e.clientY; if (isDown) { dragAndDrop.style.left = (mouseX + offsetX) + 'px'; dragAndDrop.style.top = (mouseY + offsetY) + 'px'; } });
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter