Drag And Drop Effect Using JavaScript

JavaScript Intermediate Project

When learning JavaScript, the aim is to practice in order to gain a clear understanding of specific concepts. What better way to practice than by creating real-world projects?

With that objective in mind, by the end of this article, you'll be capable of implementing the Drag And Drop Effect.

Prerequisite:

  1. Dom Manipulation

  2. Event Handling

How to Start ?

there's an image (the cool duo of Ash and Pikachu) in the left container that you want to drag into the right container.

Step 1 ( Accessing the Image )

Initially, we access the left container using the Document Object Model (DOM). Once we have access to the left container, we proceed to access the source address (src="...") of the image.

Step 2 ( Drag Operation )

Next, we apply the addEventListener() method to the first child of this container (the image of Ash and Pikachu duo). As you're aware, this method typically requires two parameters:

  1. Event name

  2. Callback function

The event that will be triggered on the image is "dragstart." This event signifies that the element has started to be dragged.

The image is dragging from first container

Step 3 ( Defining Drop Zone )

Utilizing DOM manipulation, we acquire access to the right container where we intend to drop our image. Within this container, we triggered the dragover event by utilizing the addEventListener() method, and we define a handler method as the callback function.

Step 4 ( Dropping the Image )

In this step, we release our image into the right container using the drop event, and within the event handler method (callback function), we execute the following operations:

  1. We generate an image element using document.createElement('img').

  2. We assign the source attribute (src) of this image element with the source of the Ash and Pikachu duo image obtained from the first step.

  3. We set the source attribute (src) of the image in the left container to blank (src='...'), ensuring that when our image becomes visible in the right container, it disappears from the left container.

Note: Before the drop event can be triggered, it's essential to first activate the dragover event; otherwise, the functionality will not be effective. The reason for triggering both dragover and drop events together is to prevent the accidental dropping of the image into unintended locations.