I’m using several different methods in my Javascript file to get the height of a fixed header on my site and in turn set that height as the padding for the main content (so that on load the content sits below the fixed header.
I’m using getClientBoundingRect as well as jquery. Each method returns the same result (i.e. in this instance 56), but when I inspect the element through the browser tools the height of my header is different (i.e. in this instance 98px). Only once when I reloaded the page did the Javascript return the correct height. And when I run my javascript below, directly in the console after page load, it returns the CORRECT value.
In addition, I first tried multiple reloads with my screen width under 767px to simulate mobile. None of the reloads would return the correct height of the header compared to what the browser inspector was visually showing me. So I pushed my site live and tested it on an actual iPhone in mobile safari and it worked correctly. The Javascript was returning the correct height of the fixed header and setting that value as the padding for the main content.
- I’m building a wordpress site, and I am registering my javascript file in the functions.php file.
- I’m viewing the desktop version of the site in Firefox.
- The css on the html header element has the box sizing set to border box. And even if it wasn’t set to border box, the addition of the hmtl element + margin and padding doesn’t calculate to 98px (the size of the header).
- The javascript files is being loaded before the close of the body tag.
- What could be modifying the header height before the javascript is run?
Why are the values returned by the javascript different than the actual header height in browser? I’ve read a lot of documentation but nothing that addresses why there may be an error. Nothing in the header is even close to 56px tall.
Javascript:
let headerHeight = document .getElementById("masthead") .getBoundingClientRect().bottom; // for debugging console.log(headerHeight); let siteMain = document.getElementById("primary"); if (window.innerWidth >= 767) { siteMain.style.paddingTop = headerHeight + "px"; }
Advertisement
Answer
I needed to place my javascript in a window.onLoad event listener to make sure it was being run after the entire page was loaded. I wasn’t aware that placing Javascript files in the footer would not ensure that the page was loaded before the javascript ran.