utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this?

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true>&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
           </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

Thanks.

Answer №1

Utilize the convenient wrapper for ajax-calls provided by the JQuery javascript library. Separate your modal into its own file and retrieve it using $.get from your local filesystem.

    $(function(){
        $.get('modal.html',function(html){ 
            $("#modal-placeholder").html(html);
        });
    });

If you are only utilizing JQuery for this purpose, consider using javascript's built-in ajax call as an alternative. Although not as straightforward to read or understand, it serves the same purpose:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            var modalPlaceholder = document.getElementById("modal-placeholder");
            modalPlaceholder.innerHTML= xhr.responseText;
        }
    }
};

xhr.open('GET', 'modal.html');
xhr.send(null);

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

Tips for sending a reference to a JavaScript function

While constructing a table with DataTables and utilizing AJAX as its data source, I am encountering an issue with passing a function into the AJAX parameters. The $.post() function from regular JQuery seems to always send the value of my variable when the ...

Created JSON object providing the number as a string value

I am currently facing an issue with a Vue method where it generates a JSON object from user input values before making an axios put request. The problem I'm encountering is that the JSON object generated converts numbers into strings, causing issues w ...

Divide a collection of q promises into batches and execute them sequentially

In order to achieve my objective of copying files while limiting the number of files copied in parallel based on a defined variable, I decided to divide an array of promises using calls to fs.copy into packets. These packets are then executed in series by ...

Exploring the diversity of perspectives through Angular

Currently, I am in the process of integrating multiple views in Angular to address the footer issue on a website that I am constructing. I want to ensure that the information I have been studying and attempting to replicate is accurate. Here is what I have ...

Is it possible to modify Bootstrap 4 variables using its own variables?

I am currently utilizing the latest Bootstrap 4 beta 2 and attempting to customize it by altering the variables to suit my preferences. Within my styles.scss file, I have included all necessary bootstrap imports: // Custom variables @import 'helpers ...

What is the best way to obtain the true dimensions of an HTML element?

Is there a way to determine the dimensions of a <div> element in order to accurately position it at the center of the browser window? Additionally, which browsers are compatible with this method? ...

The alignment of the table appears off on Internet Explorer, while it is perfectly centered on all other web

I'm encountering a strange issue with my table alignment on Internet Explorer. The table is offset to the right in IE, but perfectly centered in other browsers like Edge, Firefox, and mobile browsers. I am using Bootstrap for my design, but haven&apos ...

What is the most effective way to utilize bootstrap classes and their associated functions exclusively for mobile devices by using media queries?

I am encountering an issue with a table in my application that causes the UI to break when the screen width is reduced to less than 600px. To address this, I would like to implement the following bootstrap classes to add a scroll to the application: .tabl ...

Tips for showcasing HTML as code tailored to certain programming languages

While browsing the web, I stumbled upon a website that had SQL code displayed with specific classes and styles applied to it. For example, table names were colored blue when inspected. Here is a glimpse of what I encountered: https://i.sstatic.net/WAacj.p ...

Dealing with complications in the Rails asset pipeline management

I am working on a webpage that requires real-time data to be displayed. Therefore, it necessitates continuous ajax communication post page load. similar to this, jQuery -> setInterval -> $.ajax url: "some url" success: (data, te ...

The random number generator in TypeScript not functioning as expected

I have a simple question that I can't seem to find the answer to because I struggle with math. I have a formula for generating a random number. numRandomed: any; constructor(public navCtrl: NavController, public navParams: NavParams) { } p ...

Having trouble formatting the chosen date and time with the Jquery datetimepicker

I am trying to customize the date and time format while using Jquery datetimepicker. Below is my code explanation. <!doctype html> <html> <head> <title>jQuery Datepicker UI Example - Demo Preview</title> < ...

Using multiple Django FBVs to capture and save data with Ajax and jQuery

Within my Django application, I have implemented two function views - FV1 and FV2. FV1 is responsible for retrieving data from the database and populating form/formsets. In FV2, the goal is to utilize Ajax to transmit serialized data from the page (conta ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Restore original scale ratio to 1:1 following zoom

I am looking for a way to revert the image back to its original zoom level when a button is clicked using the onclick() event. I require the specific code for the onclick() event function. This is the div element in my HTML: div id="zoom"> ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...

Strange appearance of Material UI input field

https://i.stack.imgur.com/az6wt.png Does anyone have an idea why this problem is occurring? When using material UI, the default value and label for the field seem to be overlapping. Below is the code for rendering the fields: {formSchema.map((element, i ...

Have you ever wondered why the React HeroIcons architecture includes React.createElement instead of simply returning plain SVG elements?

As I integrate HeroIcons into my Next.Js app, I find myself pondering over how they have structured their package architecture. The way they return icons is like this: const React = require("react"); function ArchiveIcon(props, svgRef) { retur ...

The load method in MVC jQuery is not being properly triggered within the $(document).ready function

Currently working on an MVC5 Application.. In my project, I am trying to render two partial views by calling a controller method from $(document).ready of the main view. However, one of the methods never gets called. Below is a snippet of my view: < ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...