I was looking for an sticky footer and I found this https://gist.github.com/robertvunabandi/b66dc9872f51c93af796094e08155731
It's pretty useful but the problem is when I refresh the page the footer appears on the top first and 1 second after it takes the right place at the bottom, it's there's way to avoid that? I mean when I refresh the page the footer appears at the bottom as it should be?
window.addEventListener("load", activateStickyFooter);
function activateStickyFooter() {
adjustFooterCssTopToSticky();
window.addEventListener("resize", adjustFooterCssTopToSticky);
}
function adjustFooterCssTopToSticky() {
const footer = document.querySelector("#footer");
const bounding_box = footer.getBoundingClientRect();
const footer_height = bounding_box.height;
const window_height = window.innerHeight;
const above_footer_height = bounding_box.top - getCssTopAttribute(footer);
if (above_footer_height + footer_height <= window_height) {
const new_footer_top = window_height - (above_footer_height + footer_height);
footer.style.top = new_footer_top + "px";
} else if (above_footer_height + footer_height > window_height) {
footer.style.top = null;
}
}
function getCssTopAttribute(htmlElement) {
const top_string = htmlElement.style.top;
if (top_string === null || top_string.length === 0) {
return 0;
}
const extracted_top_pixels = top_string.substring(0, top_string.length - 2);
return parseFloat(extracted_top_pixels);
}
I guess its not a good idea to manipulate DOM-elements with JS at the page load event. Better use CSS to do the trick:
If you do it in CSS you shouldn't have this issue, plus it's very few lines of code, I made a quick mock-up as an example.
HTML:
<header>Header</header>
<main>Main</main>
<footer>Footer</footer>
CSS:
header {
background-color:blanchedalmond;
height: 10vh;
min-height: 60px;
}
main {
background-color:beige;
height: 70vh;
min-height: 800px;
}
footer {
background-color:blanchedalmond;
height: 20vh;
min-height: 200px;
position: -webkit-sticky;
position: sticky;
bottom: 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.