pro78
pro78

Reputation: 75

Header - Footer Include in another Html file

I am creating a website and I would like to be able to add external html files to another html file. I have three files. One is Header.html, the other one is the index.html, and the other one is the footer.html. What I would like is to add header and footer inside each of the new pages that I create for my website so I can update header or footer and be updated to all the pages that are included. I know, and I have done this before using server side programming language like PHP, and I have used w3schools method. Both are working, but I would like to find new ways of implement html to another html document but to be supported. I would like plain JS way, or html way. No jQuery. Hopefully someone guru out there can help me.

Thanks.

Upvotes: 0

Views: 3892

Answers (2)

subrahmanya bhat
subrahmanya bhat

Reputation: 598

try this method, this worked fine for me.

your html code..

<div id="header"></div>

<!--your body -->

<div id="footer"></div>

your javascript code

function include_header() {
document.getElementById("header").innerHTML='<object type="text/html" data="header.html" ></object>';
}
function include_footer() {
document.getElementById("footer").innerHTML='<object type="text/html" data="footer.html" ></object>';
}

call these function after DOM loaded. something like this.

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("call your functions here");
      include_header();
     include_footer();
  });

Upvotes: 1

relic
relic

Reputation: 1704

This isn't a very maintainable method for a large or complex site, fetch a markup file using ajax and append header/fooder containers to the top and bottom of the body on page load.

Sorry in advance that this answer is using jQuery, although you can do all of these steps in vanilla.

$.ajax({
    url: "/path/to/markup",
    dataType: "html",
    success: function(html) {
        $(document).ready(function() {
            $('body').prepend($(html).find('#header'));
            $('body').append($(html).find('#footer'));
        });
    }
});

Upvotes: 1

Related Questions