Making a slider form the ground up

Solution retrospective
slider
It's not enjoyable to re-implement a slider component in vanilla html despite the fact that there are already existed solution regardless of frameworks (e.g. react.js and shadcn/ui, vue.js and vuetify).
function updateSlider(clientX: number) {
if (!allowSlide) return;
const rect = scrollContainer.getBoundingClientRect();
if (clientX - rect.x - 20 > barRec.width || clientX - rect.x - 20 < 0)
return;
const sliderLeft = clientX - rect.x;
scrollProgress.style.width = sliderLeft + "px";
slider.style.left = sliderLeft + "px";
}
I cannot use layerX or offsetX because it would capture the slider button's relative position, ruining the scrolling effect. So I asked ChatGPT, it suggested that by calculating the difference between the mouse global position and the container's x coordinate, it returns the correct result.
Then, by compute the ratio between the container width and the slider position, we can know what to display.
Please log in to post a comment
Log in with GitHubCommunity feedback
No feedback yet. Be the first to give feedback on Zup's solution.
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord