I’ve been working on a project using Svelte-4 (with TypeScript) and I ran into an issue when dealing with mobile views. Specifically, I’m trying to get the layout right when the browser’s address bar hides and shows on mobile. This causes issues with setting the height of the page, and the content at the bottom goes under the navbar (this will at the bottom of the page) when the address bar is visible.
Initially, I tried setting the height of the content like this:
.screen-content {
height: calc(100vh - 72px); /* Navbar height is 72px */
}
The mobile view in Chrome’s inspect mode doesn’t simulate the address bar correctly, so the page height was all wrong when the address bar was visible when testing in mobile.
Then claude sonnet gave me this code
let navBarHeight = 0;
let isMobile = true;
$: screenHeight = isMobile
? `calc(var(--vh, 1vh) * 100 - ${navBarHeight}px - 72px)`
: `calc(var(--vh, 1vh) * 100 - ${navBarHeight}px)`;
const setViewportHeight = () => {
document.documentElement.style.setProperty('--vh', `${window.innerHeight * 0.01}px`);
isMobile = window.innerWidth < 1024;
};
onMount(() => {
setViewportHeight();
window.addEventListener('resize', setViewportHeight);
let lastScrollY = window.scrollY;
const onScroll = () => {
const currentScrollY = window.scrollY;
if (currentScrollY > lastScrollY && currentScrollY < 50) {
window.scrollTo(0, 50);
}
lastScrollY = currentScrollY;
};
window.addEventListener('scroll', onScroll);
setTimeout(() => {
const navBarElement = document.querySelector('.navigation-bar');
if (navBarElement) {
navBarHeight = navBarElement.clientHeight;
}
}, 0);
});
onDestroy(() => {
window.removeEventListener('resize', setViewportHeight);
window.removeEventListener('scroll', onScroll);
});
--removed the height css in the style.
Am I missing something or is there a better approach??
I don't want to mess up the page UI with some AI generated code. Though I get what is happening here I want to here some thoughts regarding this by some experienced front end devs.
Top comments (0)