Nnnnn
Nnnnn

Reputation: 133

Keeping modal only at one place (Bootstrap)

I am building a website using bootstrap and i have to use the same modal on every page. Right now i have to copy the whole code into every html and then it becomes available to every page but this is isn't the ideal way of doing things so i would like if anyone suggests me a way that i don't have to copy the same html code to every file. I want a way that the same html code becomes available to all pages while it is kept only at one place. I cannot post my code here but i'll try to tell you my problem exactly.

<!-- navbar for website -->
1 html code
<!-- sign in and login modal(buttons are on navbar) -->
2 html code
<!-- main body -->
3 html code
4 html code
5 html code
<!-- footer for website -->
6 html code
7 html code

For example according to above block navbar, modal and footer(1,2,6,7 lines) remain same for every page. How can I put all that elsewhere and just link it somehow like css files are linked(something like that). I can give you more information just ask in comments(other than my exact code).

Upvotes: 1

Views: 52

Answers (2)

Darryl RN
Darryl RN

Reputation: 8228

There are two ways to accomplish your goal:

  1. Using Javascript

<script>
function includeModal() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      } 
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}
</script>

Then call it

<script>
   includeModal();
</script>

  1. Using HTML

<div w3-include-html="modal.html"></div>

Upvotes: 2

Nauman Moazzam
Nauman Moazzam

Reputation: 158

At first you need to divide your html, like make another file for only Footer i.e. Footer.html, and header.html etc.

Then use JQuery to include them.

<html> 
 <head> 
  <script src="jquery.js"></script> 
   <script> 
     $(function(){
      $("#includedContent").load("header.html"); 
      });
   </script> 
  </head> 
   <body> 
    <div id="includedContent"></div>
  </body> 
 </html>

The jQuery .load() documentation is here

Upvotes: 0

Related Questions