html5 draggable hide original element
You may succeed this with a hacky solution. The native draggability doesn't allow CSS styles like: opacity:0;
, visibility:hidden
or display:none
.
But you can do it using: transform:translateX(-9999px)
.
function startDrag(e) { let element = e.target; element.classList.add('hide');}function endDrag(e) { let element = e.srcElement; element.classList.remove('hide');}
.draggable { border-radius: 4px; background: #CC0000; width: 40px; height: 40px;}.hide { transition: 0.01s; transform: translateX(-9999px);}
<div class="draggable" draggable="true" ondragstart="startDrag(event)" ondragend="endDrag(event)"/>
I've updated your JSFiddle with the solution.
[EDIT]:
Updated JSFiddle example with Andrew Hedges suggestion by using requestAnimationFrame
instead setTimeout
.
[EDIT 2]:
Updated with a better solution by Jason Yin adding transition
CSS property instead using requestAnimationFrame
, it moves the processing from scripting to rendering.
Since simply setting visibility: hidden
doesn't work, I found another somewhat hacky solution: set visibility: hidden
one millisecond after the drag event starts.
function startDrag(e) { setTimeout(function() { e.target.style.visibility = "hidden"; }, 1);}function endDrag(e) { setTimeout(function() { e.target.style.visibility = ""; }, 1);}
body { display: inline-block; outline: 1px solid black;}.draggable { border-radius: 4px; background: #CC0000; width: 40px; height: 40px;}
<div class="draggable" draggable="true" ondragstart="startDrag(event)" ondragend="endDrag(event)"></div>
This could be achieved without hacky trick from the previous answers.
The key point is to listening to the drag
event, instead of the dragstart
.
//listen to drag event, not dragstart!document.querySelector(".draggable").addEventListener("drag", (e)=>{ e.target.classList.add("dragging");});document.querySelector(".draggable").addEventListener("dragend", (e)=>{ e.target.classList.remove("dragging");});
.draggable { width: 200px; height: 30px; background-color:#5856d6; text-align:center; line-height:30px;}.dragging { background: transparent; color: transparent; border: 1px solid #5856d6;}
<div draggable="true" class="draggable">Drag me!</div>