Search code examples
javascriptjqueryhtmlcssfooter

Calling a function after dynamic content is loaded


My main objective is to place a footer which stays at bottom. My footer code is working fine if content height exceeds the screen height but when a page with less content arrives, it shows a huge gap between footer and screen bottom. So i am dynamically getting the content height and then placing it afterwards.

$(window).on('load', function() {
    console.log(window.innerHeight);
    console.log($(".content").height());
    alert("hi");

    if((window.innerHeight - $(".content").height()) < 70 ) $("footer").css({"position": "absolute", "top": window.innerHeight-90});
});

If is use this code in google chrome console after page is loaded, it works perfectly, but when placed in code, $(".content").height() is giving a constant value.


Solution

  • You don't need to do this with JS.

    You can do this in css using flex-box and forcing the min-height to always fill the viewport with the vh unit.

    .Site {
      margin: 0;
      display: flex;
      min-height: 100vh;
      flex-direction: column;
    }
    
    .Site-content {
      flex: 1;
    }
    
    header { background-color: lime; }
    
    footer { background-color: red; }
    <body class="Site">
      <header>header content</header>
      <main class="Site-content">site content</main>
      <footer>footer content</footer>
    </body>