javascripthtmlcssfooterastrojs

How to be sure that the body has a height before running a script


I want to execute this script within the astro framework to adjust the placement of my footer at the end of the page if the page is shorter than the viewport (if there is a better way tell me, but it's not the problem here):

    window.onload = function () {
        const footer = document.querySelector('footer')
        if (!footer) return
        const bodyHeight = document.body.clientHeight
        const windowHeight = window.innerHeight
        if (bodyHeight < windowHeight) {
            footer.style.position = 'absolute'
            footer.style.bottom = '0'
            footer.style.width = '100%'
        }
    }

But because it's asynchronous document.body.clientHeight is equal to 0 9 times on 10 and window.onload handler change nothing. I also tried body.onload but same thing.

Here is my crappy hotfix:

    window.onload = function () {
        const footer = document.querySelector('footer')
        if (!footer) return
        footer.style.display = 'none'
        setTimeout(function () {
            const bodyHeight = document.body.clientHeight
            const windowHeight = window.innerHeight
            if (bodyHeight < windowHeight) {
                footer.style.position = 'absolute'
                footer.style.bottom = '0'
                footer.style.width = '100%'
            }
            footer.style.display = 'block'
        }, 100) // Let the page load first
    }

Solution

  • So this doesn't help me about the asynchronous part but here is my fix for the footer in css.

    :root {
      --header-height: 6.5rem;
      --footer-height: 5rem;
    }
    
    main {
      min-height: calc(100vh - var(--header-height) - var(--footer-height));
      padding: 40px 40px 0 40px;
      box-sizing: border-box;
    }
    

    I just add to add a main at my base Astro layout