I'm trying to add this feature to my nav bar https://www.w3schools.com/howto/howto_js_sticky_header.asp.
The difference is that my website has the header in another HTML file called menu.html and it is imported using jquery, more precisely this command.
$(function (){
$("#header").load("/structureFiles/menu.html");
});
Moreover, this function is in a separate .js file with the function to add the "sticky" bar
window.onload= function(){
var topNav = document.getElementById("topMenu");
var sticky = topNav.offsetTop;
console.log("top menu: " + sticky);
}
When I try to retrieve the element using getElementById
i obtain
Cannot read property 'offsetTop' of null
.
On the other hand, if I try to use jquery with $(window).scroll
, the element offset is always zero. Any idea?