I have created index.html file and added header and footer sections. I want to show them on my other pages like about, contact but I don't want to copy them on all webpages. Please guide me how can I do it using vanilla JavaScript.
Copy your header and footer code to header.txt and footer.txt files and then just add this code to your JavaScript file. Don't forget to:
You can also add header and footer code to separate JavaScript files as you like.
const fetchHeader = async () => {
try {
const res = await fetch("./header.txt");
const template = await res.text();
const parse = new DOMParser();
const html = parse.parseFromString(template, "text/html");
const header = html.querySelector("body header");
document.body.prepend(header);
} catch (err) {
console.log(err);
}
};
const fetchFooter = async () => {
try {
const res = await fetch("./footer.txt");
const template = await res.text();
const parse = new DOMParser();
const html = parse.parseFromString(template, "text/html");
const footer = html.querySelector("body footer");
document.body.append(footer);
} catch (err) {
console.log(err);
}
};
fetchHeader().then(fetchFooter);
If you want to add any kind of functionality like toggling menu on click, you can do this:
const getElements = () => {
const nav = document.querySelector(".navbar");
const menuBtn = document.querySelector("#menu-btn");
menuBtn.addEventListener("click", () => {
nav.classList.toggle("active");
});
window.addEventListener("scroll", () => {
nav.classList.remove("active");
});
};
Now call this function after calling fetchHeader function because menu is in header
fetchHeader().then(getElements).then(fetchFooter);
// OR
fetchHeader().then(getElements);
fetchFooter();
You can use custom elements, by now it should be supported by major browsers:
<html>
<head>
<script src="./custom-elements.js"></script>
</head>
<body>
<app-header></app-header>
</body>
</html>
// custom-elements.js
class AppHeader extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<div style='border:2px solid red; padding:5px'>
This is my header
</div>
`
}
}
window.customElements.define('app-header', AppHeader)
Another may be simpler way of writing JavaScript
const headerElement = document.querySelector("header");
const footerElement = document.querySelector("footer");
const fetchHeader = async () => {
try {
const res = await fetch("./header.txt");
const template = await res.text();
headerElement.innerHTML = template;
} catch (err) {
console.log(err);
}
};
const fetchFooter = async () => {
try {
const res = await fetch("./footer.txt");
const template = await res.text();
footerElement.innerHTML = template;
} catch (err) {
console.log(err);
}
};
fetchHeader();
fetchFooter();