Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives:

  1. The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "beforeAcceptingTerms" division is visible prior to this action.
  2. Upon clicking on the Accept Terms modal button, the "afterAcceptingTerms" division should become visible while the "beforeAcceptingTerms" division is concealed.

While the following code snippet represents our initial Bootstrap 5 setup, it does not successfully implement the required toggling of div classes as outlined above.

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Modal Popup Page</title>
    <link href="/assets/css/bootstrap.min.css" rel="stylesheet"> 
    <script src="/assets/js/popper.min.js"></script>
    <script src="/assets/js/bootstrap.min.js" ></script>
  </head>
  <body>
    <div class="wrapper" id="beforeAcceptingTerms">
      <section class="content-section">
        <p>To access the content of this page, you need to click on the "I agree to the terms" button.</p>
      </section>
  </div>
  <div class="wrapper" id="afterAcceptingTerms">
    <section class="content-section">
      <p>Page content will be displayed here after accepting the terms by clicking the modal's Accept button and closing the modal.</p>
    </section>
  </div>
<!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel"   data-bs-backdrop="static" aria-hidden="true">
      <div class="modal-dialog" style="position: fixed;bottom: 0;left: 0;right: 0;">
          <div class="modal-content">
        <div class="modal-body">
            By using this site, you certify that you agree to our <a href="/terms">Terms of Use</a>.
        </div>
        <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="localStorage.setItem('acceptTerms',1)">I agree to the Terms.</button>
        </div>
      </div>
      </div>
    </div>
    <script>
      let acceptTerms = localStorage.getItem('acceptTerms');
      if(acceptTerms != 1){
        var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
        myModal.show()
      }
    </script>
  </body>
</html>

Answer №1

You neglected to include CDNs instead of your local files.

(I appended a button to clear local storage data for testing purposes).

What have I modified?

        // Window onload event to display your content if users have accepted terms
        // calling checkTerms() function
        window.onload = (event) => {
            checkTerms();
        };

        const afterAcceptingTerms = document.getElementById('afterAcceptingTerms');
        const acceptTermsButton = document.getElementById('acceptTermsButton');

        // Added a listener to your accept terms button
        // removing inline onclick element attribute
        acceptTermsButton.addEventListener('click', function() {
            termsAccepted();
        });
        // Here we manage what to do when the user clicks on the accept terms button
        // in this case with try/catch to prevent critical errors, it's good to send
        // errors like that (in a catch block) to a server so you stay on top of any errors users may experience
        function termsAccepted() {
            try {
                localStorage.setItem('acceptTerms', 1);
            } catch (error) {
                alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
            }
            afterAcceptingTerms.classList.remove('none');
        }
        // Function called when the window loads !! To check if the user has accepted the terms !
        // I'm using try/catch because this is critical, if the localStorage can't be accessed
        // your content won't be shown
        function checkTerms() {
            let val = '';
            try {
                val = localStorage.getItem('acceptTerms');
            } catch (error) {
                alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
            }
            if (val === '1') {
            afterAcceptingTerms.classList.remove('none');
            } else {
                var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
                myModal.show()
            }
        }

I also added a .none class with (display:none) to your #afterAcceptingTerms element, it was crucial for this element to start with display:none. We are going to remove that class programmatically:

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Modal Popup Page</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4e4343585f585e4d5c6c19021e021f">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2909d9d868186809382b2c7dcc0dcc1">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .none {
            display: none;
        }
    </style>
  </head>
  <body>
    <div class="wrapper" id="beforeAcceptingTerms">
      <section class="content-section">
        <p>You must click on the "I agree to the terms button" in order to see the content on this page.</p>
      </section>
      <button id="clearData">Clear storage data</button>
  </div>
  <div class="wrapper none" id="afterAcceptingTerms">
    <section class="content-section">
      <p>The page content goes here.  But this is only visible because you clicked on the Accept button on the modal in order to get the modal to go away.</p>
    </section>
  </div>
<!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel"   data-bs-backdrop="static" aria-hidden="true">
      <div class="modal-dialog" style="position: fixed;bottom: 0;left: 0;right: 0;">
          <div class="modal-content">
        <div class="modal-body">
            By using this site, you certify that you agree to our <a href="/terms">Terms of Use</a>.
        </div>
        <div class="modal-footer">
              <button type="button" id="acceptTermsButton" class="btn btn-secondary" data-bs-dismiss="modal">I agree to the Terms.</button>
        </div>
      </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e3938c93938691cd8990a3d2cdd2d5cdd2">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script>
        var clearData = document.getElementById('clearData');
        clearData.addEventListener('click', function() {
            localStorage.clear();
        });

        window.onload = (event) => {
            checkTerms();
        };

        const afterAcceptingTerms = document.getElementById('afterAcceptingTerms');
        const acceptTermsButton = document.getElementById('acceptTermsButton');

        acceptTermsButton.addEventListener('click', function() {
            termsAccepted();
        });

        function termsAccepted() {
            try {
                localStorage.setItem('acceptTerms', 1);
                afterAcceptingTerms.classList.remove('none');
            } catch (error) {
                alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
            }
        }

        function checkTerms() {
            let val = '';
            try {
                val = localStorage.getItem('acceptTerms');
                if (val === '1') {
                afterAcceptingTerms.classList.remove('none');
                } else {
                    var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
                    myModal.show()
                }
            } catch (error) {
                alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
            }
        }
    </script>
  </body>
</html>

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

The numbering in the list does not align vertically with the corresponding content

I am attempting to create an ordered list with collapsible sections inside the li elements. The goal is to display basic information about a specific context, and when clicking on a link, additional details are shown. While the code is functional, I am fac ...

Changing the size of icons in an Alert using Material UI with React

Recently, Material UI unveiled the new 'Alert' component. Everything seems to be working well, except for the fact that I can't find a way to adjust the size of the icon. Here is my code snippet: <Snackbar open={true}> <Alert ...

Having trouble shutting down the window using Electron and Socket io

I embarked on a chat application project using NodeJS and Socket.io, everything was running smoothly. However, when I decided to integrate my app into the Electron framework, the chat window opened but I encountered an issue with the close button not func ...

The Enigmatic Gap Amidst Flex Elements

I have a situation where two divs are placed within a flex container. However, the second div is incorrectly aligning to the right side of the page rather than next to the first div. Despite the default values for flex-flow being row and justify-content b ...

How to swap one image for another using jQuery on click

I have a question about updating images on an HTML page using jQuery. Below is the code I am currently using: $(document).ready(function() { $("#img-1").click(function() { var imgsrc = $(this).attr('src'); $(".click-img").attr('s ...

Using jQuery to delay hiding for 2 seconds

Hey there! I'm facing an issue with my code. The function is supposed to make #aboutPopOut slide to the left, and then after a 2-second delay, fade out the fadescreen by hiding it. The sliding part works fine, but the waiting and hiding do not seem to ...

NextJS Input Field causing a strange "Hydration Error indicating server HTML should not contain a <div> within a <form>", perplexingly occurring only in Chrome and exclusively on my personal computer

Looking for some assistance with a website I'm working on using NextJS and TailwindCSS. There seems to be a pesky little issue in my code that's causing some trouble. Below is the code snippet for the MainContent section of the page: "use c ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

The transition effect is not activated when using the MUI Drawer with react-router-dom

My goal was to merge the persistent drawer similar to the example on the MUI website with react-router-dom. However, I encountered a problem where the transition effect no longer seems to work properly. The paragraph does not resize to accommodate the open ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...

Issues arise when the condition fails to function correctly during the process of form

I am currently working on a question from my elder brother's question paper, but I am struggling to solve it. The task is to create a form with two text fields, a radio button, and a submit button. The text fields should be named "account number" and ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...

Looping through a nested for loop within an HTML table

I am currently working on generating a dynamic table using Lists of varying sizes. My first list is a List of Cars List<Car>. I have successfully placed the names of different car companies in the header. Next, I have a List<List<CarSales>& ...

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Align content to the bottom using Bootstrap 4

Looking for help with aligning content to the middle and bottom on a full-page bootstrap layout? The first page has a background image in the first div, and a darker layer on top in the second div. <div class="h-100 w-100"> <div class="h-100 w-10 ...

Adjust padding of elements based on scrolling movements

Currently, I am attempting to adjust the padding of a specific element based on how far down the page the user scrolls. Ideally, as the user scrolls further down the page, the padding will increase, and as they scroll back up, the padding will decrease. H ...

Restrict page scrolling to the vertical position of a specified div [Using jQuery, javascript, and HTML]

Currently, I am in the process of developing a personal website that features numerous expandable items. My goal is to restrict the page scrolling to the height of the expanded item once it is opened. I do not want users to be able to scroll above or below ...