Drag And Drop - Javascript

Sergio Rueda's photo
Sergio Rueda
·Oct 20, 2020·

3 min read

This article shows the use draggable property along with the events this property triggers when used.

draggable is a global attribute. It is an attribute that indicates whether an element can be dragged or not. It can only have either of these values: true or false.

  • true Element can be dragged.
  • false Element cannot be dragged.


  <div draggable='true' id='dragger'>Dragging div</>

the following is incorrect

  <div draggable id='dragger'>Dragging div</>

There are a few different ways to use this property along with its firing events. I chose to add events to my documents, that way whenever a draggable event occurs it will be handle by the program.

Events that fire on a draggable source

  • ondragstart
    This event only occurs when the user starts to drag any given element.
  • ondrag This event occurs while the element is being dragged.
  • ondragend This event occurs when user finishes dragging the element.

Events that fire on a draggable target/drop

  • ondragenter fires when element being dragged enters the target/drop area.
  • ondragover fires when element being dragged is over the target/drop area.
  • ondragleave fires when element being dragged leaves the target/drop area.
  • ondrop fires when element being dragged is dropped on the target/drop area.

While dragging an element the ondrag fires every 350 milliseconds.

Draggable code follows:

/* Events fired on the drag target */
document.addEventListener("dragstart", function(event) {

/* this happens when we first start dragging an element.  */
/* it only assigns the element id to 'Text' */
document.addEventListener("drag", function(event) {
 let source = document.getElementById(; = 'lightblue';

/* This happens while we are dragging the element */
/* we are only setting the background of the source */
/* Events fired on the drop target */
/* We do not want this event to do its default processing */

document.addEventListener("dragover", function(event) {

Finally we have have an event that handles most of the work logic for our purpose in this program

document.addEventListener("drop", function(event) {
  var data = event.dataTransfer.getData("Text");
  var el = document.getElementById(data);

  if ( == "target" ) {
    if ( === el.textContent)
    { = el.textContent; = 'red';
      el.hidden = true; = 'white'; = 'green';


  if (correctAnswers === len)
        let success = document.getElementById('successMessage'); = 'block';

Please see live code below:

Thank you for reading this article. I hope you like it and it will help with your learning journey.

Let's Connect

Next article: undecided

Share this