Code Snippets
JavaScript snippets
Same header/footer on every page
You can load your header/footer via javascript. This is helpful so you don't have to update the code for your header/footer on every single page when you make a change.
Read...Automatic Tab Title Suffix
for example, changing "about me" in the browser tab to "about me | your site name"
Show/Hide
const tabTitle = document.title;
if (tabTitle !== "YOUR HOME TITLE") {
document.title = tabTitle + " | some text";
}
The if makes sure that the title of your homepage doesn't end up like "site name | site name"
Highlight active links
You can give the class "active" to any active navigation links automatically
Show/Hide
const linkElements = document.querySelectorAll("nav a");
[...linkElements].forEach((el) => {
const href = el.getAttribute("href").replace(".html", "").replace("/public", "");
if (href == "/" || href == "/index.html") {
if (window.location.pathname == "/") {
el.classList.add("active");
}
} else {
if (window.location.href.includes(href)) {
el.classList.add("active");
}
}
});
(You will need to change the selector for your navigation links (default: "nav a").)
Automatic Table of Contents
(example on this page)
Show/Hide
In your HTML, add this line whereever you want it to be:
<div id="toc"></div>
The JavaScript:
const container = document.querySelector("#toc");
if (!container) return;
const allHeadings = document.querySelectorAll("h2");
if (allHeadings.length < 2) return;
let output = "<b>Table of Contents:</b><ol>";
[...allHeadings].forEach((headingEl) => {
const title = headingEl.innerHTML;
const link =
headingEl.getAttribute("id") ||
encodeURI(
title
.replaceAll(" ", "-")
.replaceAll("#", "")
.replaceAll("&", "")
.replaceAll(/<[^>]*>?/gm, "")
.replaceAll("--", "-")
).toLowerCase();
headingEl.setAttribute("id", link);
output += `<li><a href="#${link}">${title}</a></li>`;
});
container.innerHTML = output + "</ol>";
Change the selector (default: "h2") to any selector that targets the headings you want to turn into the table of contents.
You can override the automatically generated ID of a heading by simply setting a custom one in the HTML.
HTML/CSS Snippets
Color Filter over Image
(examples see here)
Show/Hide
HTML:
<div class="pink-image"><img src="..." /></div>
CSS:
.pink-image {
position: relative;
img {
filter: brightness(1.1) contrast(1.3);
}
&::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
background: pink;
opacity: 0.25;
pointer-events: none;
}
}
You can adjust the filters, the background color and the opacity of the background color.