0

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 getElementByIdi 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?

Steve
  • 1
  • 3
  • I'd start by changing `window.onload` to `$(document).ready()` and see if that makes a difference https://stackoverflow.com/questions/3698200/window-onload-vs-document-ready – user9263373 Feb 11 '18 at 23:19
  • 1
    Possible duplicate of [How to select an element loaded through the jQuery load() function?](https://stackoverflow.com/questions/4450825/how-to-select-an-element-loaded-through-the-jquery-load-function) – Obsidian Age Feb 11 '18 at 23:29
  • ^ `.load()` is asynchronous. You need to wait until the content has loaded before trying to target it. – Obsidian Age Feb 11 '18 at 23:29
  • Nothing changed, i continue to get Cannot read property 'offsetTop' of null. Seems like that i can't retrieve an element imported from another file – Steve Feb 11 '18 at 23:54

1 Answers1

-2

Have you tried something like this:

$(window).scroll(function(){
    $("#header").css(
    {
        position: $("#header").offset().top - window.scrollY > window.scrollY ? 
            "fixed" : "static",
        top: 0
    });
});
tobi
  • 37
  • 3
  • I don'r want manipulate the css of #header element but of the element inside it that i'm going to load using jquery – Steve Feb 11 '18 at 23:56