hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.7k stars 424 forks source link

Feature request - Action option or global handling of 'outside' events #656

Open lb- opened 1 year ago

lb- commented 1 year ago

Summary

The action options and global listeners are incredibly powerful. However, it would be great to fill in a common use case gap of an event that triggers only when outside the element is clicked.

Example use cases include focus traps, tooltips that close when something else it focused or clicked on, modals that can close when the user clicks outside the modal, dynamic form behaviour where blur is not suitable.

Proposed usage

<div data-controller="tooltip" data-action="click@outside->tooltip#close focus@outside->tooltip#close" data-tooltip-attached-to-value="#some-id">
  Tooltip content
</div>
<div data-controller="focus-trap" data-action="focus@outside->focus-trap#keep keyup.tab->focus-trap#forward keyup.tab+shift->focus-trap#back">
  An overlay around a modal. 
</div>

Alternative solutions

  1. Don't implement this - instead it could be built as a custom event option, maybe just document it
  2. Implementation via an action filter (like keyboard events) or a built in option (like prevent)

Links

seb-jean commented 1 year ago

It would be great to have an 'outside' event. It would be useful for dialog and dropdown.

lb- commented 1 year ago

Put this PR together, hope that is ok. https://github.com/hotwired/stimulus/pull/695