0

I want to call header.html and footer.html in every page of html using javascript. I tried the code Make header and footer files to be included in multiple html pages, but this is not working for me

Here is the same code,

<html>
<head>
<title>hi</title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script> 
$("#header").load("header.html"); 
$("#footer").load("footer.html"); 
</script> 
</head>
<body>
<div id="header"></div><br />
<div id="content">
  Main Content
</div><br />
<div id="footer"></div>
</body>
</html>

I downloaded jquery-1.11.1.min.js from this http://jquery.com/download/ site. Please, help me to correct this code.

Community
  • 1
  • 1
PyPerl
  • 55
  • 2
  • 7
  • This has been asked before: http://stackoverflow.com/questions/18712338/make-header-and-footer-files-to-include-multiple-html-pages – Drew Kennedy Nov 12 '14 at 18:54
  • Can you update your post with your current file structure? And does the console give you any errors? – Tim Nov 12 '14 at 18:56
  • Possible duplicate of [Multiple distinct pages in one HTML file](https://stackoverflow.com/questions/8211128/multiple-distinct-pages-in-one-html-file) – rodude123 Oct 25 '19 at 14:19

3 Answers3

2

You need to wrap your code in a document ready function:

<script>
    jQuery(document).ready(function($){
        $("#header").load("header.html");
        $("#footer").load("footer.html");
    });
</script>

Otherwise your code will execute before #header and #footer are available.

max
  • 76,662
  • 13
  • 84
  • 137
  • Hi, this is working with mozilla but not with chrome – PyPerl Nov 13 '14 at 15:06
  • Hi, I check the console. Here is the error XMLHttpRequest cannot load header.html. Received an invalid response. Origin 'null' is therefore not allowed access. index.html:1 header.html loaded – PyPerl Nov 13 '14 at 20:26
  • It´s not an issue with this code - it´s because you are using chrome with file URLs. http://stackoverflow.com/questions/4208530/xmlhttprequest-origin-null-is-not-allowed-access-control-allow-origin-for-file – max Nov 14 '14 at 02:52
1

Wrap your code in a document ready block

jQuery(document).ready(function($) {
  $('#header').load('header.html', function () {
    console.log('header.html loaded')
  });
  $('#footer').load('footer.html', function () {
    console.log('footer.html loaded')
  });
})
elzi
  • 4,734
  • 6
  • 32
  • 59
1

The problem is that your DOM is not loaded when you call the script to load the elements.

Jquery cant find the $("#header") and #footer because the DOM is not ready.

Try this just above the </body> tag:

jQuery(document).ready(function($) {
 $("#header").load("header.html"); 
 $("#footer").load("footer.html"); 
}  
ChrisL
  • 90
  • 7