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 (<a></a>) 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.

  1. modal-sm
  2. modal-lg
  3. 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.

Note: Modify the external CSS and Script accoding to your file directories.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Universal Bootstrap Modal using jQuery and Ajax</title>
  8. <link rel="stylesheet" href="./assets/css/bootstrap.css">
  9.  
  10. html,
  11. body {
  12. height: calc(100%);
  13. }
  14. </style>
  15. </head>
  16.  
  17. <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  18. <div class="container-fluid">
  19. <a class="navbar-brand" href="https://sourcecodester.com">SourceCodester</a>
  20. </div>
  21. </nav>
  22. <div class="container py-2">
  23. <h2 class="border-bottom border-dark">Universal Bootstrap Modal using jQuery and Ajax</h2>
  24. </div>
  25. <div class="wrapper h-75 d-flex align-items-center">
  26. <div class="container">
  27. <!-- Modal Buttons -->
  28. <div class="row justify-content-center gx-grid-2 gx-grid-3 row-cols-4">
  29. <div class="col p-1">
  30. <a class="btn btn-primary w-100 btn-sm rounded-0 modal-button" data-title="Test Content 1" data-modal-size="modal-xl" href="test.html" type="button">Test Content Modal 1</a>
  31. </div>
  32.  
  33. <div class="col p-1">
  34. <a class="btn btn-primary w-100 btn-sm rounded-0 modal-button" data-title="Test Content 2" data-modal-size="" href="test2.html" type="button">Test Content Modal 2</a>
  35. </div>
  36.  
  37. <div class="col p-1">
  38. <a class="btn btn-primary w-100 btn-sm rounded-0 modal-button" data-title="Test Content 3" data-modal-size="modal-lg" href="test3.html" type="button">Test Content Modal 3</a>
  39. </div>
  40.  
  41. <div class="col p-1">
  42. <a class="btn btn-primary w-100 btn-sm rounded-0 modal-button" data-title="Test Content 4" data-modal-size="modal-sm" href="test4.html" type="button">Test Content Modal 4</a>
  43. </div>
  44. </div>
  45. <!-- Modal Buttons -->
  46. </div>
  47. </div>
  48.  
  49. <!-- Universal Modal-->
  50. <div class="modal" tabindex="-1" id="universal_modal">
  51. <div class="modal-dialog modal-dialog-centered">
  52. <div class="modal-content rounded-0">
  53. <div class="modal-header py-1 px-2">
  54. <h5 class="modal-title"></h5>
  55. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  56. </div>
  57. <div class="modal-body">
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. <!-- Universal Modal-->
  63.  
  64. </body>
  65. <script type="text/javascript" src="./assets/js/jquery-3.6.0.js"></script>
  66. <script type="text/javascript" src="./assets/js/bootstrap.js"></script>
  67. <script type="text/javascript" src="./assets/js/script.js"></script>
  68.  
  69. </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
  1. <h1 style="margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding: 0px; font-family: DauphinPlain; font-size: 70px; line-height: 90px; color: rgb(0, 0, 0); text-align: center;">Lorem Ipsum</h1>
  2. <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: &quot;Open Sans&quot;, Arial, sans-serif;">"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
  3. <h5 style="margin: 5px 10px 20px; padding: 0px; font-size: 12px; line-height: 14px; text-align: center; color: rgb(0, 0, 0); font-family: &quot;Open Sans&quot;, Arial, sans-serif;">"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
  4. <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: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: center; background-color: rgb(255, 255, 255);">
  5. <div id="Content" style="margin: 0px; padding: 0px; position: relative; color: rgb(0, 0, 0); font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: center;">
  6. <div id="bannerL" style="margin: 0px 0px 0px -160px; padding: 0px; position: sticky; top: 20px; width: 160px; height: 10px; float: left; text-align: right;"></div>
  7. <div id="bannerR" style="margin: 0px -160px 0px 0px; padding: 0px; position: sticky; top: 20px; width: 160px; height: 10px; float: right; text-align: left;"></div>
  8. <div class="boxed" style="margin: 10px 28.7969px; padding: 0px; clear: both;">
  9. <div id="lipsum" style="margin: 0px; padding: 0px; text-align: justify;">
  10. <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
  11. 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
  12. 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>
  13. <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
  14. 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
  15. 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>
  16. <p
  17. 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
  18. 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>
  19. <p
  20. 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
  21. gravida. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aenean id maximus sapien. Quisque eget diam velit.</p>
  22. <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
  23. 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>
  24. </div>
  25. </div>
  26. </div>
test2.html
  1. <p>This is a sample content 2</p>
test3.html
  1. <div class="alert alert-info"> This is sample content 3.</div>
test4.html
  1. <div class="alert alert-warning"> This is sample content 4 </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

  1. function show_universal_modal($title, $link, $size = '') {
  2. // Checking if link is empty then return false
  3. if ($link == '') {
  4. alert("Content Link is null");
  5. return false;
  6. }
  7. $('#universal_modal').find('.modal-dialog').removeClass('modal-sm')
  8. $('#universal_modal').find('.modal-dialog').removeClass('modal-lg')
  9. $('#universal_modal').find('.modal-dialog').removeClass('modal-xl')
  10. $('#universal_modal').find('.modal-dialog').addClass($size)
  11. $('#universal_modal').find('.modal-body').html("<center>Loading data. Please wait ...</center>")
  12. $('#universal_modal').find('.modal-title').html($title)
  13. $('#universal_modal').modal('show')
  14.  
  15. // Fetching content via Ajax
  16. $.ajax({
  17. url: $link,
  18. error: err => {
  19. console.log(err)
  20. $('#universal_modal').find('.modal-body').html("<div class='alert alert-danger'>Error fetching content.</div>")
  21. },
  22. success: function(resp) {
  23. var container = $('<div class="container-fluid">')
  24. container.html(resp)
  25. $('#universal_modal').find('.modal-body').html(container)
  26. }
  27. })
  28.  
  29.  
  30. }
  31.  
  32. $(function() {
  33. // Modal button click action
  34. $('.modal-button').click(function(e) {
  35. e.preventDefault()
  36. var size = $(this).attr('data-modal-size') !== undefined ? $(this).attr('data-modal-size') : '';
  37. show_universal_modal($(this).attr('data-title'), $(this).attr('href'), size)
  38. })
  39.  
  40. })

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.

  1. <a class="btn btn-primary w-100 btn-sm rounded-0 modal-button" data-title="New Content Title" data-modal-size="" href="new_file.html" type="button">Button Name</a>

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