Skip to main content

How do I render a (Stimulus) modal without user interaction?

Javascript • Asked by Jeff Helman

When a data value in my view meets certain criteria (e.g.: "< 0"), I want to render a modal (which is configured using Stimulus).

I know this is a noobish question, but I'm not finding obvious answers in my Googling/SO spelunking.


The easiest solution is to add a data map object to the controller element, eg. <div data-controller="modal" data-modal-preload="true"></div>. Based on your criteria you can either add "true" of false (or null)" there, eg data-modal-preload="<%= x < 0 ? true : false %>".

Then within your modal controller's connect(), check for this value to be set and true, if so fire the function that opens/shows your modal, eg. if (this.data.get("preload") && this.data.get("preload") == "true") { this.open() }.


Many thanks, Eelco!


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.