References

Beginner-friendly references for web development, with live, editable examples.

The HTML ondragleave event

Event All modern browsers Updated
Quick answer

The HTML ondragleave attribute runs JavaScript when a dragged item leaves a valid drop target. It is an inline handler for the dragleave event; in modern code prefer addEventListener('dragleave', …).

Overview

The ondragleave event attribute runs JavaScript when a dragged item leaves a drop target. In JavaScript the event itself is named dragleave — drop the on prefix when you call addEventListener.

It is part of the native HTML drag-and-drop API. The handler receives a DragEvent whose dataTransfer object carries the dragged data. One rule trips everyone up: you must call event.preventDefault() in the ondragover handler of a target, or it will not accept a drop.

You can wire this up with the inline ondragleave HTML attribute, but the modern, recommended approach is element.addEventListener('dragleave', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element ondragleave="handler()">…</element>

element.addEventListener('dragleave', handler);

Best practices

  • Prefer element.addEventListener('dragleave', handler) over the inline ondragleave attribute — it separates behavior from markup and allows multiple handlers.
  • Call preventDefault() in ondragover so the element can act as a drop target.
  • Set and read the payload through event.dataTransfer.
  • Provide a keyboard-accessible alternative — native drag-and-drop is hard to use without a mouse.

Frequently asked questions

What is the ondragleave event?
It runs JavaScript when a dragged item leaves a drop target. In JavaScript the event is named dragleave.
Why is my drop not working?
You must call event.preventDefault() in the ondragover handler, otherwise the element rejects the drop.
How do I pass data between dragged and dropped elements?
Use event.dataTransfer.setData() when the drag starts and getData() when it drops.
Should I use the ondragleave attribute or addEventListener?
Prefer addEventListener('dragleave', …) in JavaScript. The inline ondragleave attribute works but mixes behavior into the markup and allows only one handler per element.