Creating Universal Bootstrap Modal using jQuery and Ajax Tutorial
In this tutorial, we will tackle about How to Create a Universlal Bootstrap Modal using jQuery and Ajax. The modal that we are going to create is a modal that can be reusable or can display different content from another file. This technique is very helpful to optimize your file size and this will prevent the redundancy of writting the modal elements. The universal Bootstrap Modal that we will create, will have a dynamic title, content, and size. We will use an HTML a tag () as the button that will initiate the modal.
Modal Button Must Have
The modal button must have a modal-button class name and contains the following attribute.
- data-title = "" - This is where the universal bootstap modal script will get the Modal Title
- href = "" - This attribute contains the link of the file content.
- data-modal-size = "" (optional) - This attribute declares the size of modal.
Modal Sizes
The sizes modal will be same as the bootstrap modal sizes. These are the following allowed value for the data-modal-size = "" attribute.
- modal-sm
- modal-lg
- modal-xl
Getting Started
Since we are going to create a universal Bootstrap Modal, kindly download the Bootstrap. Download also the jQuery either minified or uncompressed. Please do not use the slim version of the jQuery so the Ajax will work properly.
Creating the Interface
First we will create the index file for our web application. This file contains our bootstrap modal template.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="./assets/css/bootstrap.css">
- <style>
- html,
- body {
- height: calc(100%);
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="container py-2">
- </div>
- <div class="wrapper h-75 d-flex align-items-center">
- <div class="container">
- <!-- Modal Buttons -->
- <div class="row justify-content-center gx-grid-2 gx-grid-3 row-cols-4">
- <div class="col p-1">
- </div>
- <div class="col p-1">
- </div>
- <div class="col p-1">
- </div>
- <div class="col p-1">
- </div>
- </div>
- <!-- Modal Buttons -->
- </div>
- </div>
- <!-- Universal Modal-->
- <div class="modal" tabindex="-1" id="universal_modal">
- <div class="modal-dialog modal-dialog-centered">
- <div class="modal-content rounded-0">
- <div class="modal-header py-1 px-2">
- </div>
- <div class="modal-body">
- </div>
- </div>
- </div>
- </div>
- <!-- Universal Modal-->
- </body>
- </html>
In the script above, there are 4 different bootstrap modal buttons that have unique content file links. These are the sample scripts of each content file. Kindly save the files according to the file name above scripts.
test.html- <h4 style="margin: 10px 10px 5px; padding: 0px; font-size: 14px; line-height: 18px; text-align: center; font-style: italic; color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif;">"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
- <hr style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0)); color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; font-size: 14px; text-align: center; background-color: rgb(255, 255, 255);">
- <div id="Content" style="margin: 0px; padding: 0px; position: relative; color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; font-size: 14px; text-align: center;">
- <div class="boxed" style="margin: 10px 28.7969px; padding: 0px; clear: both;">
- <div id="lipsum" style="margin: 0px; padding: 0px; text-align: justify;">
- <p style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed sapien semper, euismod justo quis, maximus erat. Fusce faucibus, tellus sed congue auctor, sapien turpis varius erat, quis fermentum lectus libero sit amet metus. Pellentesque
- in bibendum est. Donec nec dui eget risus facilisis vulputate eu et erat. Nam blandit vulputate volutpat. Sed tincidunt malesuada porttitor. Fusce at sapien mattis, elementum nibh eu, auctor nisl. Fusce in dolor rutrum, convallis neque
- ac, interdum nulla. Nullam rutrum, quam vel finibus congue, purus orci interdum nibh, non maximus velit augue non justo. Aenean dui justo, tempus nec ex at, vulputate pharetra est.</p>
- <p style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px;">Duis lectus tortor, dapibus nec ante in, convallis rutrum dui. Proin sit amet venenatis purus. Quisque posuere, libero ut gravida ultrices, enim augue venenatis metus, at tincidunt enim lectus et velit. Morbi odio ante, dapibus et feugiat
- eu, commodo non nisi. Suspendisse eu lorem dolor. Integer quis maximus nibh. Sed condimentum nisi arcu, eget cursus nulla ultrices eu. Ut ac malesuada metus. Ut maximus orci eget nulla porta laoreet. Fusce nunc est, porttitor sit amet
- ligula eget, porttitor gravida quam. Nam dolor turpis, pellentesque id aliquam in, volutpat sit amet urna. Proin gravida ipsum non odio suscipit, ac tempus enim consequat. Praesent aliquet auctor nulla, in consequat elit porttitor eget.</p>
- <p
- style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px;">Nulla eget aliquet massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed quis dapibus purus, eget dignissim elit. Aliquam consequat consectetur lorem, quis mollis odio condimentum sed. Nullam interdum
- vitae purus sit amet euismod. Morbi justo ex, volutpat dignissim laoreet sit amet, mattis id nunc. Maecenas porta justo vel augue maximus, at molestie tortor mattis. Donec fringilla massa nec arcu sodales, vel malesuada massa lacinia.</p>
- <p
- style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px;">Nulla mollis ut nunc at faucibus. Suspendisse eget massa in nisl molestie finibus. In aliquet at orci id malesuada. Donec vehicula, augue a varius sagittis, nunc metus iaculis eros, id iaculis urna sapien at tellus. Nulla elementum pellentesque
- gravida. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aenean id maximus sapien. Quisque eget diam velit.</p>
- <p style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px;">Donec vitae diam sed lectus malesuada tincidunt at id odio. Curabitur lacinia lorem ac iaculis luctus. Maecenas eget felis auctor diam ullamcorper consectetur. Suspendisse tincidunt in magna in euismod. Curabitur posuere tellus at
- urna volutpat, vitae dapibus velit blandit. Sed tempus porttitor leo, et blandit felis vehicula ut. Suspendisse vulputate venenatis mauris at auctor. Praesent at sagittis ligula.</p>
- </div>
- </div>
- </div>
Creating the Scripts
The code below is the script that contains the universal modal initiator script and buttons action script. Save the file as script.js
- function show_universal_modal($title, $link, $size = '') {
- // Checking if link is empty then return false
- if ($link == '') {
- alert("Content Link is null");
- return false;
- }
- $('#universal_modal').find('.modal-dialog').removeClass('modal-sm')
- $('#universal_modal').find('.modal-dialog').removeClass('modal-lg')
- $('#universal_modal').find('.modal-dialog').removeClass('modal-xl')
- $('#universal_modal').find('.modal-dialog').addClass($size)
- $('#universal_modal').find('.modal-body').html("<center>Loading data. Please wait ...</center>")
- $('#universal_modal').find('.modal-title').html($title)
- $('#universal_modal').modal('show')
- // Fetching content via Ajax
- $.ajax({
- url: $link,
- error: err => {
- console.log(err)
- $('#universal_modal').find('.modal-body').html("<div class='alert alert-danger'>Error fetching content.</div>")
- },
- success: function(resp) {
- var container = $('<div class="container-fluid">')
- container.html(resp)
- $('#universal_modal').find('.modal-body').html(container)
- }
- })
- }
- $(function() {
- // Modal button click action
- $('.modal-button').click(function(e) {
- e.preventDefault()
- var size = $(this).attr('data-modal-size') !== undefined ? $(this).attr('data-modal-size') : '';
- show_universal_modal($(this).attr('data-title'), $(this).attr('href'), size)
- })
- })
DEMO VIDEO
There you go. You can now test the simple web application that we created in your end. To test a new modal content kindly create html file and add new modal button in the index.php like below.
That ends this tutorial. You can also download the working source code that I created for this tutorial. The download button is located below. I hope this will help you with what you are looking for and for your future projects. Explore more on this website for more Tutorials and Free Source Codes.
Enjoy Coding :)
Add new comment
- 568 views