Thanks to all the contributors.
I am trying to add a modal overlay over bootstrap carousel on initial load to collect emails before allowing access to the slides in the carousel. Previously, I used JQuery and Turbolinks:
$(document).on("turbolinks:load", function() {
if ($("#carousel-example-generic").is(':visible') ) {
$('#myModal').modal({show: true, backdrop: 'static', keyboard: false});
}
});
and this html:
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="modal fade" id="myModal" > </div>
</div>
But now, I want to use Stimulus.js but can't get the modal overlay to display on the bootstrap carousal even when I add an event listener for DOMContentLoaded, it is not used by stimulus.js.
<div data-controller="presentation">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false"
data-target="presentaion.displayModal" data-action="DOMContentLoaded->presentation#showModal" > </div>
</div>
The only way I have been able to get the modal display to work is to add the initialize method
to Stimulus.js controller that then calls another method that renders the modal as shown in presentation_controller.js below:
import {Controller} from 'stimulus'
import * as $ from 'jquery/dist/jquery'
import 'bootstrap/dist/js/bootstrap';
export default class extends Controller {
initialize() {
this.showModal();
}
get carouselModalElement() {
return this.targets.find('displayModal')
}
showModal(){
if ($("#carousel-example-generic").is(':visible') ) {
$('#myModal').modal({show: true, backdrop: 'static', keyboard: false});
}
}
}
Is this the recommended way to do this with Stimulus.js or is there a better approach to achieve this.
@mankind I am not an expert with Stimulus but it is my understanding that what you are doing by calling showModal() in the initialize() function is what I would have done.
You might want to have a look at this issue to be sure to select the proper place between initialize() and connect() #75
Yes, the right place to do this kind of thing is in the initialize or connect callback.
There鈥檚 no need to use the DOMContentLoaded event with Stimulus. HTML can appear on the page at any time, not just on the initial page load. Catching that is exactly what the lifecycle callbacks are for :)
Most helpful comment
Yes, the right place to do this kind of thing is in the
initializeorconnectcallback.There鈥檚 no need to use the
DOMContentLoadedevent with Stimulus. HTML can appear on the page at any time, not just on the initial page load. Catching that is exactly what the lifecycle callbacks are for :)