0

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);
}
Davy0324
  • 21
  • 4
  • Use CSS to set the position to the bottom? This can likely be all done via CSS anyway, but if this is how you want to do it, that's fine too. – Heretic Monkey Jun 15 '20 at 19:58

2 Answers2

0

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:

How to make a sticky footer using CSS?

Peter
  • 314
  • 1
  • 11
0

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;
  }
Yaakov David
  • 133
  • 8