How to get Bootstrap modal pop up on page load?

Issue

I have a static HTML page with a basic modal from Bootstrap docs:

   <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

In my app.js file I have an app.get() method serving this file:

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/modal.html");
});

I would like this modal to pop up on page load, how do I do that?

Solution

try using DOMContentLoaded event. Something like this:

<script>
    window.addEventListener('DOMContentLoaded', function () {
        var myModal = new bootstrap.Modal(document.getElementById('exampleModal'), {
            keyboard: false
        });
        myModal.show();
    });
</script>

NOTE: The above code is not tested but you’d need something like this.

Answered By – riazosama

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published