Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 22088  / 8 Years ago, sat, april 2, 2016, 12:00:00

When starting to drag an element using HTML5 draggable attribute, original element is still visible, so I end up having two elements visible instead of one.



How can I do to have only the element being dragged visible (the original one should be momentarily hidden).



<script>
function startDrag() {
// hide initial element
}

function endDrag() {
// reset initial element
}
</script>

<div class=draggable draggable=true
ondragstart=startDrag(event)
ondragend=endDrag(event)
></div>


Here's a jsfiddle to show the problem https://jsfiddle.net/gjc5p4qp/


More From » html

 Answers
17

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.


[#62719] Thursday, March 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;