Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you link to an HTML file?

Tags:

html

My website has the same navigation menu throughout, instead to rewriting the HTML code for every page, can I link to a second HTML file (that contains the nav HTML code) like you would with CSS? Or will that create problems?

like image 827
Emmet Arries Avatar asked Dec 01 '22 16:12

Emmet Arries


2 Answers

Simple way would be to put the header part in a separate html file.

Now load this file in html code using jQuery load function like

$("#headerDiv").load("header.html")

Know that, this will require web server because load function sends a request to server.

Check out the code sample:

demo.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> 
   $(function(){
    $("#headerDiv").load("header.html");
   });  
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>

header.html

<div >
    <a>something</a>
    <a>something</a>        
</div>
like image 156
pritesh Avatar answered Dec 04 '22 10:12

pritesh


That is called HTML includes, and YES, it is possible

<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
  myHTMLInclude();
  function myHTMLInclude() {
    var z, i, a, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
      if (z[i].getAttribute("w3-include-html")) {
        a = z[i].cloneNode(false);
        file = z[i].getAttribute("w3-include-html");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
            a.removeAttribute("w3-include-html");
            a.innerHTML = xhttp.responseText;
            z[i].parentNode.replaceChild(a, z[i]);
            myHTMLInclude();
          }
        }      
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
      }
    }
  }
})();
</script>

NOTES

HTML doesn't have a simple include mechanism (except for frames like iframe, which have side effects).

A better solution would be to use Server-Side includes, which is the preferred way of adding common parts to your document, on the server, of course.

like image 43
Pmpr.ir Avatar answered Dec 04 '22 11:12

Pmpr.ir