Last active
November 27, 2017 09:13
-
-
Save arielsalminen/8d14411a70a141a2be6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* DRAG'N'DROP DRAG IMAGES FOR @jonikorpi | |
* (this is a quick'n'dirty example, I might’ve typoed some stuff) | |
* | |
* In addition to all this you might have to listen for "drop", "dragenter", "dragleave" & "dragover" | |
* events on the container where the dropping happens and on "ondragover" also call the removeDragImage(); | |
*/ | |
var dragImage, dragging; | |
// Creates the drag image with JavaScript | |
function createDragImage(event) { | |
var bounds = dragging.getBoundingClientRect(); | |
var width = bounds.width; | |
var height = bounds.height; | |
dragImage = dragging.cloneNode(true); | |
dragImage.classList.remove("transformed-styles-classes-or-something"); | |
dragImage.classList.add("drag-image"); | |
dragImage.style.width = width; | |
dragImage.style.height = height; | |
event.dataTransfer.setDragImage(dragImage, width / 2, height / 2); | |
document.body.appendChild(dragImage); | |
} | |
// Removes the drag image once drag is finished | |
function removeDragImage() { | |
if (dragImage && dragImage.parentNode) { | |
dragImage.parentNode.removeChild(dragImage); | |
} | |
} | |
// When the dragging starts… | |
function ondragstart(event) { | |
dragging = event.target; | |
createDragImage(event); | |
} | |
// When the dragging ends… | |
function ondragend(event) { | |
event.preventDefault(); | |
removeDragImage(); | |
} | |
// INIT: | |
// Select all draggable elements | |
var elements = document.querySelectorAll("[draggable=true]"); | |
// For all those elements… | |
[].forEach.call(elements, function(element) { | |
// Add necessary event listeners | |
element.addEventListener("dragstart", ondragstart, false); | |
element.addEventListener("dragend", ondragend, false); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment