How I Put the Scroll Percentage in the Browser Title Bar
Publikováno: 12.5.2020
Some nice trickery from Knut Melvær.
Ultimately the trick boils down to figuring out how far you’ve scrolled on the page and changing the title to show it, like:
document.title = `${percent}% ${post.title}`
Knut’s trick assumes React and installing an additional library. I’m sure that library does all kinds of smart stuff, but if you’re looking to do this “vanilla” style, I’d probably rock something like this…
const percentLabel = document.querySelector("#percent");
const originalTitle = document.title;
window.addEventListener("scroll", () ={
… Read article “How I Put the Scroll Percentage in the Browser Title Bar”
The post How I Put the Scroll Percentage in the Browser Title Bar appeared first on CSS-Tricks.
Some nice trickery from Knut Melvær.
Ultimately the trick boils down to figuring out how far you’ve scrolled on the page and changing the title to show it, like:
document.title = `${percent}% ${post.title}`
Knut’s trick assumes React and installing an additional library. I’m sure that library does all kinds of smart stuff, but if you’re looking to do this “vanilla” style, I’d probably rock something like this…
const percentLabel = document.querySelector("#percent");
const originalTitle = document.title;
window.addEventListener("scroll", () => {
let scrollTop = window.scrollY;
let docHeight = document.body.offsetHeight;
let winHeight = window.innerHeight;
let scrollPercent = scrollTop / (docHeight - winHeight);
let scrollPercentRounded = Math.round(scrollPercent * 100);
percentLabel.innerHTML = scrollPercentRounded;
document.title = `(${scrollPercentRounded}%) ${originalTitle}`;
});
Here’s a project, and here’s the deployed site so you can see it in action.
Direct Link to Article — Permalink
The post How I Put the Scroll Percentage in the Browser Title Bar appeared first on CSS-Tricks.