Skip to main content

EmptyDomController

Purpose

Mainly for use with TurboStreams or AJAX loaded content that modifies a container interactively. When interactions mutate the DOM and add/remove content, detect when the container you attach the controller to becomes empty/not empty.

You can then style the controller, or show a nice placeholder when the container is empty, rather than showing empty space.

Actions

ActionPurpose
--

Targets

TargetPurposeDefault
container (Optional)The DOM element whose childList to observe for emptinessthe controller root element

Classes

ClassPurposeDefault
empty (Optional)The class to apply to the attached element when it is empty-
notEmpty (Optional)The class to apply to the attached element when it is not empty-

Values

ValueTypeDescriptionDefault
scopeSelector (Optional)StringA CSS selector to pass to querySelectorAll to limit what elements are included in the count of empty/not-emptyAll child elements of controller element

Events

EventWhenDispatched onevent.detail
empty-dom:emptyWhen the subtree of the attached element becomes emptyThe controller element-
empty-dom:not-emptyWhen the subtree of the attached element is no longer emptyThe controller elementcount - The number of matching elements that are now present

Side Effects

None

How to Use

The controller emits an event dom:empty when the container becomes empty, and dom:not-empty when it is no longer empty (and for every DOM update that means it is still not empty). Use those events to hook up other Stimulus actions. Alternatively, set a particular class when the watched container becomes empty or filled.

You can also scope what the controller watches for inside the container using a CSS selector in the data-empty-dom-scope-selector-value attribute.

The selector you specify will be used to querySelectorAll the children/subtree of the container you attach the controller too, and fire the dom:empty and dom:not-empty events when the results of the query are empty/not empty.