Launching Bootstrap 5 Modal Automatically when the Page Loads

I'm currently working on setting up an automatic modal that pops up when the page loads for a school project. I've been using Bootstrap 5, but most of the examples I found online are based on older versions. The specific modal I'm referring to is called

Vertically Centered Cookies Modal
. To implement this, I've utilized a Bootstrap CDN as well as the Popper Bundle from https://getbootstrap.com/. Here's the code snippet I've used:

<!DOCTYPE HTML>
<html lang="en-AU">
<head>
    <!-- Require Meta Tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        
    <!-- CDN - Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53313c3c27202721322313667d637d61">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"gt;
    
    <!-- Title -->
        <title>Title Here</title>
    
    <!-- Webpage Icon -->
        <link rel="shortcut icon" href="Images\Pilot640_Logo_Symbol.ico"/>
        

</head>

<body>      

<!-- Nav Bar -->
<nav class="navbar navbar-expand-sm bg-secondary navbar-white">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">
        <img src="Images\Pilot640_Logo_Symbol.ico" alt="Logo" style="width:100px;" class="rounded-pill">
        </a>
    </div>
</nav>

<!-- Header Section -->
<header> 

</header> 

<!-- Vertically Centered Cookies Modal -->

<div class="modal-dialog modal-dialog-centered" id="onload">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Do You Want Cookie? We Want Yours! 🍪</h5>
        </div>
        <div class="modal-body">
            This site uses cookies to personalize the content for you.
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
    </div>
</div>


<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9cbc6c6dddadddbc8d9e99c8799879b">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    
<!--Modal JS Script --> 
<script type="text/javascript">
    $(window).load(function(){
        $('#onload').modal('show');
    });
</script>
    
</body>
</html>

If anyone has insights on what might be causing any issues or has suggestions for improvement, I would greatly appreciate the help.

Answer №1

Vanilla JavaScript Option

The structure of the HTML can stay as is, with no requirement to include jQuery

<script type="text/javascript">
    window.onload = () => {
      const myModal = new bootstrap.Modal('#onload');
      myModal.show();
    }
</script>

Answer №2

Greetings and welcome to the wonderful Stackoverflow community.

Upon reviewing your query, it appears that you must rectify the modal dialog code snippet initially. The crucial aspect you missed was the first line of the modal. It is imperative to incorporate the id in that particular line rather than in the modal-dialog div.

<div class="modal fade" id="onload" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <!-- Make sure to include this line in your code -->
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Do You Want Cookie? We Want Yours! 🍪</h5>
            </div>
            <div class="modal-body">
                This site uses cookies to personalize the content for you.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div> <!-- And do not forget about the relevant closing div tag -->

Furthermore, ensure to import jquery into your code. Failure to do so will result in jquery code segments not functioning correctly within your HTML file. Ultimately, instead of utilizing a jquery onload event listener, opt for the native VanillaJS window.onload event to activate your modal.

<!-- Import jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- Incorporate Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="711315059e999e996e2f28129c829c90">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"gt;</script>

<!-- Modal JS Script -->
<script type="text/javascript">
    window.onload = () => {
        $('#onload').modal('show');
    }
</script>

By adhering to these steps, your bootstrap modal should operate smoothly as intended.

Answer №3

<script type="module">
  import * as bootstrap from 'bootstrap';
  window.onload = () => {
      const modalWindow = new bootstrap.Modal('#onload');
      modalWindow.show();
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What exactly does the ::before pseudo-element accomplish?

After reviewing the documentation, I believe I have a good grasp of the purpose of ::before and ::after. It seems that they are typically used in conjunction with other elements. However, the webpage I am examining contains the following code: <body> ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

Why is the text not displaying in ReactJS when using Enzyme?

Can you please assist me in understanding why my test case is not running in React when using enzyme? I have installed enzyme js and followed this tutorial at Below is the code I am using: import React from 'react'; import Hello from './ ...

Opera's extra space feature allows users to comfortably browse the

I'm attempting to insert a progress bar inside a td element within my table. Below is the code: <td style="width: 150px;"> <div style="height: 16px; max-height: 16px; overflow: hidden; border: 1px solid #80C622;"> < ...

What could be the reason why the Bootstrap toggle feature is not functioning properly in my code?

It seems that the toggle feature is not working correctly, even though I believe I have the correct order of jQuery and Bootstrap. It appears that this issue has been encountered by others as well, but I hoped my earlier assumptions would be enough to reso ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

When two divs are activated, the third div goes into invisible mode

I attempted this code, but it doesn't appear to be functioning correctly. if(div1)&& (div2)==display:none { div3=display:none; } else { div3=display:block; } ...

Incorporate a button within the input field

Looking to customize my search form with the search button on the right side, similar to this: https://i.sstatic.net/lwmig.png Below is the code for my current form setup: <form action="search.php" method="post" class="index-search-form"> ...

HapiJS commences an extended duration background process

Is there a way to achieve the functionality of a PHP exec function in HapiJS? I have a scenario where the user submits a processing job that requires running in the background for a significant amount of time. An essential requirement is to provide the us ...

Utilize a counter to iterate the name repeatedly

echo "<td>".'<input type="text" name="date_from" class="datepicker"/>'."</td>"; Is there a way to utilize a counter to repeat the name attribute and then store it using $_POST[]? ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Is there a way to perfectly align the content at the center of the section?

I'm trying to ensure that the content in each section is centered. What is the correct way to achieve this? Should I focus on the containers/rows for alignment? I have tried placing the alignment properties in different elements (section, container, r ...

What is the best way to assign an ID to the initial table header in an asp:DataGrid for CSS styling purposes?

I am looking for a way to customize the first element in the table headers row using CSS without relying on :first_child selector. Example Code: <asp:TemplateColumn HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"> <Heade ...

Exploring the journey of History.js and Same-Origin Policy leading to HTTPS encryption

Utilizing history.js, I am attempting to push a state change from an HTTP site like: http://www.example.com/some/resource ...to a secure site (payment page), such as: https://www.example.com/payment/for/some/resource However, Safari is throwing thi ...

Why isn't my div displaying in JavaScript?

Currently working on a project for the Odin Project front-end web development. My task involves creating a grid using javascript/jQuery. I attempted to use the createElement method but have encountered an issue in making the div visible within the html. Am ...

What is the method to display a caret in regular HTML text with the use of JavaScript?

Currently, I am studying JavaScript and aiming to develop a typing game similar to typeracer.com. The goal of the game is to type accurately and quickly without errors. In this game, users input text into a box, and JavaScript then compares their inputs w ...

Webpack is ejected from watch mode

Currently, I am in the process of learning React and have decided to use webpack alongside it. However, I seem to be facing an issue with webpack when it comes to the watch mode. It builds the files once but then halts. The console output reflects the foll ...

Select Box in HTML now supports the addition of a Background Image, enhancing

Currently, I am trying to customize the select option box using HTML and CSS. My main goal is to incorporate a scroll feature into the option box. However, I have encountered an issue where the image of the checked box remains visible on the screen. Below ...

Directional Div CSS Transition

Is it feasible to determine the starting direction of a CSS transition? I've designed a div that enlarges in height when hovered over; however, it's situated at the bottom of the page, causing the scrollbar to extend downward. Ideally, I would ...