ArticleZip > Html5 Draggable Hide Original Element

Html5 Draggable Hide Original Element

Html5 Draggable: Hide Original Element

Have you ever wondered how to make an HTML element draggable? It's a handy feature that can enhance user experience on your website. In this tutorial, we'll show you how to use HTML5 to make an element draggable and hide the original element once it's dragged. Let's dive in!

To begin, you will need a basic understanding of HTML, CSS, and JavaScript. If you're new to web development, don't worry! We'll guide you through each step.

First, create the HTML structure for the draggable element:

Html

<div id="draggableElement">Drag me!</div>
<div id="dropzone">Drop here!</div>

In this example, we have a div element with the id "draggableElement" that we want to make draggable. The "draggable" attribute set to "true" enables the element to be draggable.

Next, add the JavaScript code to make the element draggable:

Javascript

const draggableElement = document.getElementById('draggableElement');
const dropzone = document.getElementById('dropzone');

draggableElement.addEventListener('dragstart', (event) =&gt; {
  event.dataTransfer.setData('text/plain', draggableElement.innerHTML);
  setTimeout(() =&gt; {
    draggableElement.style.display = 'none';
  }, 0);
});

dropzone.addEventListener('dragover', (event) =&gt; {
  event.preventDefault();
});

dropzone.addEventListener('drop', (event) =&gt; {
  event.preventDefault();
  const data = event.dataTransfer.getData('text/plain');
  const newElement = document.createElement('div');
  newElement.textContent = data;
  dropzone.appendChild(newElement);
});

In the code above, we have added event listeners to handle the drag and drop functionality. When the user starts dragging the element, the 'dragstart' event is triggered. We set the data to be transferred and hide the original element by setting its display to 'none'.

The 'dragover' event is used to allow the drop action on the dropzone element. Finally, the 'drop' event is triggered when the user drops the draggable element onto the dropzone. We retrieve the data and create a new element in the dropzone with the transferred content.

Now that you have the code in place, let's test it out! Open your HTML file in a browser, and you should see the draggable element "Drag me!". Try dragging it to the dropzone area "Drop here!", and you will see the original element disappearing while a new element appears in the dropzone.

Congratulations! You have successfully made an HTML element draggable and hidden the original element using HTML5 drag and drop functionality. Feel free to customize the code further to suit your needs and explore more possibilities with drag and drop interactions on your website. Happy coding!

×