How to hide your element
If you want to hide your element, you can use the CSS property visibility:hidden
or display:none
.
I recommend using the visibility
property because it's hides an element without changing the layout of the document. But, if you're element have childrens and you want to hide them to, you need to set up visibility:inherit
on each of childrens.
When to hide it
You were right to use the dragstart
event. But the clone of the element who is created by the draggable attribute appears at the end of the dragstart
event.
Because JavaScript engine is a single-threaded interpreter if you choose to hide it in here, you're element will be masked as its clone which will copy the property visibility:hidden
. In fact, to avoid this you need to hide it after the creation of the clone in the Javascript callstack.
To do it, use the setTimout()
function and set it to 0 ms. This way, the masking of the original element is put at the end of the stack, after the creation of his clone.
At the end of the drag, to make it reappear, you just need to set the element visible by calling visibility:visible
in the dragend
event.
Code exemple
For you're exemple, the code can look like this :
<div
class="draggable"
draggable="true"
ondragstart="startDrag(event)"
ondragend="endDrag(event)"
style="background: #e66465; color:white; width:80px; height:20px; text-align:center;">
Drag me
</div>
<script>
function startDrag(e) {
setTimeout(function(){
e.target.style.visibility = "hidden";
}, 0);
}
function endDrag(e){
e.target.style.visibility = "visible";
}
</script>