Get super confident at JavaScript. Javascript Icon

I promise to change your JavaScript skills!

Active States with Drag Enter and Leave Events in JavaScript

So you’re diving into the world of Drag & Drop APIs in JavaScript, but now it’s time to make things a little more functional for the end user.

Typically when you “drag” something into a draggable area, you’ll want to provide some UI feedback that something’s happening.

For this, we’re going to simply add an active class to the draggable area.

For this, we’ll need to hook into the dragenter and dragleave events.

The Drag & Drop API is sometimes seen as a little overcomplex, due to the masses of possible events and their confusing names. That said, these are two important ones that you can use specifically for toggling active states in the UI.

First, let’s grab a reference to a DOM element we’ll consider draggable:

const dropzone = document.querySelector('.dropzone');

From here, bind some events:

dropzone.addEventListener('dragenter', () => {});
dropzone.addEventListener('dragleave', () => {});

Here, we can use an arrow function with implicit or explicit return as we’ll not be referencing the this keyword, however you could if you like.

All we’re going to do is add an active class, which I’ll bind these styles:

.active {
  background: #ebfff6;
  border-color: #24b373;
}

For this, we simply need to reference event.target and use the classList API to add or remove the class:

const dropzone = document.querySelector('.dropzone');

dropzone.addEventListener('dragenter', (e) =>
  e.target.classList.add('active')
);
dropzone.addEventListener('dragleave', (e) =>
  e.target.classList.remove('active')
);

Here’s a working demo, give it a try by dragging the pink box into the draggable area:

And that’s it! The dragenter and dragleave events make perfect sense for this and respond really nicely with the classList API.

That’s all you need, no need to overcomplicate things.

🏆 P.S. check out my latest JavaScript courses if you’re serious about taking your skills to the top.

Thanks for reading, happy dragging!

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover