How Toggle BootStrap 5 Modal Without Button Click

I’m trying to learn Bootstrap 5 and I’m trying to toggle a modal on my page without using a button. By default a modal is hidden and normally the user needs to click on a button to show it. Instead of that I would like to automatically show the modal as soon as the page loads without the user clicking a button. I tried to do this by first grabbing the modal ID and then setting its aria-hidden attribute to false using the Javascript function setAttribute(‘aria-hidden’, ‘false’). Needless to say this does not work.

REPLY

Does this help.

var myModal = new bootstrap.Modal(document.getElementById("exampleModal"));
myModal.show();

From the documentation here:

Hi Paul,
Thank you so much for your response, your solution works great. The only question I have is how come your script throws an error when I place it in the head tag. The following is in my head tag

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
<script>
   document.addEventListener('DOMContentLoaded', (event) => {    
     var myModal = new bootstrap.Modal(document.getElementById("#Instructions"));
     myModal.show();
   });
</script>

I’m guessing that DOMContent Loaded is run before the bootstrap script is loaded.

DOMContentLoaded may fire before your script has a chance to run, so it is wise to check before adding a listener.

Is there a reason you can’t place the JS at the end of the html before the closing body tag where it belongs ?

Otherwise I think you may need to use load rather than DOMcontent loaded but maybe a JS guru (@Paul_Wilkins ) could confirm :slight_smile:

Hi Paul, I looked up the differences between DOMContentLoaded and load and I’ve found out that DOMContentLoaded will not wait for all scripts to be loadded while load will wait for all DOM and scripts to be loaded. However, when I use load in my addEventlistener in the head tag it does not work. I found a solution in a post on stack overflow https://stackoverflow.com/questions/16404380/why-doesnt-document-addeventlistenerload-function-work-in-a-greasemonkey-s which stated document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener()
instead. I tried using window.addEventListener() as suggested by this post and sure enough the script works even though I’m using DOMContentLoaded in addEventListener in the head tag.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.