My Development Notes

Programming Made Easier


How to create reusable Header and Footer using JavaScript?

There are a few different ways to create reusable header or footer in a website using JavaScript so that you don’t have to repeat the code. Let’s explore :

Method 1 (using template tag)

I’m using an HTML template tag to hold content first. Content inside this tag is hidden by default. You have to use JavaScript to display the content inside the <template> tag. Here’s how it works :

<template id="header" class="headerJS">
      <a href="#">About</a>
      <a href="#">Contact</a>
      <a href="#">Testimonials</a>
</template>
const headerEl = document.getElementById("header");
document.body.appendChild(headerEl.content);

// this code displays the template

Method 2 (directly using JS)

You can directly insert the HTML codes inside JavaScript file using the following codes and then use the custom <template> tag anywhere on the HTML file like so :

const headerElement = document.createElement("template");

headerElement.innerHTML = `
  <a href="#">About Us</a>
  <a href="#">Contact Us</a>
  <a href="#">Notice</a>
  <a href="#">Privacy</a>
`;

document.body.appendChild(headerElement.content);
// first build the JS template then use the template in HTML file

You can now use the <template> tag to display the results like so :

<body>
    <template></template>
    <script src="index.js"></script>
</body>

You can now also use <slot> element to customize the template even more.

Method 3 (using custom element)

This method gives you more flexibility to work with :

<template id="main-menu">
      <style>
        p {
          color: white;
          background-color: black;
          padding: 5px;
        }
      </style>
      <p>FTH Logistics</p>
</template>
customElements.define(
  "header-footer",
  class extends HTMLElement {
    constructor() {
      super();
      let template = document.getElementById("main-menu");
      let Navbox = template.content;

      const shadowRoot = this.attachShadow({ mode: "open" });
      shadowRoot.appendChild(Navbox.cloneNode(true));
    }
  }
);

In this code I’ve created custom element called <header-footer> which can now be used anywhere inside the HTML file to show the contents like so :

<header-footer></header-footer>

Posted

in

by

Tags:

Leave a Reply