Today we are starting a new series of tutorials, but with a twist. We are leaving Alpinejs behind and instead using vainilla JavaScript to create our components.
About: Front End designer.
Today we are starting a new series of tutorials, but with a twist. We are leaving Alpinejs behind and instead using vainilla JavaScript to create our components.
Another way to add Scroll Progress Bar in React
ScrollProgressBar.jsx component
import React, { useEffect, useState } from "react";
const ScrollProgressBar = () => {
const [scrollProgress, setScrollProgress] = useState(0);
useEffect(() => {
const calculateScrollProgress = () => {
const scrollTop = window.scrollY;
const scrollHeight =
document.documentElement.scrollHeight - window.innerHeight;
const progress = (scrollTop / scrollHeight) * 100;
setScrollProgress(progress);
};
const scrollListener = () => {
requestAnimationFrame(calculateScrollProgress);
};
window.addEventListener("scroll", scrollListener);
return () => {
window.removeEventListener("scroll", scrollListener);
};
}, []);
return (
<div
className="fixed top-0 left-0 h-1 bg-sky-300"
style={{ width: `${scrollProgress}%` }}
/>
);
};
export default ScrollProgressBar;
Import and Use ScrollProgressBar in the Navbar component or Where you like to add Scroll Progress Bar
Your use cases confuse me -
That sounds fine!
I don't think it's likely people would be using their cart in a manner where the page is long enough for this to matter, and the position on the page is likely irrelevant since most carts put their main CTA at the top.
This is the same as the Content marketing case.
People don't use progress indicators for social media feeds because they are typically infinite scroll and the bar will jump back and forth a lot as you read!
My suggestion would be to inject the element with Javascript in the first place rather than baking it into the HTML, and omitting the Tailwind aspect, which is adding a dependency but not any actual benefit. If you're creating and modifying the element with script, you can add style attributes the same way and keep it entirely separate, so you can inject the progress bar into any page you like with a function call.