Skip to content

Mouse click that started inside modal should not close modal #278

@hugovandevliert

Description

@hugovandevliert

When using the Modal component, if a user starts a drag operation inside the modal (e.g., selecting text in an input field or dragging a range slider) and their mouse moves outside the modal boundary, the modal closes unexpectedly when they release the mouse button.

Reproduction steps

  1. Open a modal with an input field containing text
  2. Click and hold inside the input field to start selecting text
  3. While holding the mouse button, drag the cursor outside the modal boundary
  4. Release the mouse button
  5. Expected: Text selection completes, modal stays open
  6. Actual: Modal closes

The current backdropClose implementation closes the modal on any click event that occurs on the dialog backdrop. When a user starts their interaction inside the modal (mousedown inside) but finishes outside (mouseup on backdrop), the browser still fires a click event on the backdrop, triggering the modal to close.

I've successfully fixed this by extending the Modal controller and overriding the backdropClose method to track where the mousedown event started, and only close the modal if both the mousedown and click events occurred on the backdrop:

connect() {
  super.connect();
  this.mouseDownTarget = null;
}

backdropClose(event) {
  // Track where mousedown occurred
  if (event.type === 'mousedown') {
    this.mouseDownTarget = event.target;
    return;
  }

  // Only close if both mousedown and click happened on the backdrop
  if (event.type === 'click') {
    const isBackdrop = event.target.nodeName === 'DIALOG';
    const mouseDownOnBackdrop = this.mouseDownTarget?.nodeName === 'DIALOG';

    if (isBackdrop && mouseDownOnBackdrop) {
      this.close();
    }

    this.mouseDownTarget = null;
  }
}

This also requires updating the modal template to listen for both events:

data-action="mousedown->modal#backdropClose click->modal#backdropClose"

This prevents accidental closures while still allowing users to click the backdrop to dismiss the modal. I'm happy to submit a PR with this fix if you're open to it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions