Search code examples
javascripthtmlheader

My automatic header with javascript won't close in any page


So a few days ago, I had a small problem. My website has a header normal menu, and I wanted to made it automated with javascript. When I try to find bugs I found a little problem you can see in the image:

Problem image

Normal menu image

My menu working well all the time but after I created javascript code:

        <!-- header begin -->
    <div id="nav-placeholder">
        <script>
            $.get("nav.html", function(data) {
                $("#nav-placeholder").replaceWith(data);
            });

        </script>
    </div>
    <!-- header close -->

This code made my menu load from the nav.html file, okei finally. When I load my menu from nav.html it won't work well, but if I use the code normally in the index.html file it works great.

Maybe I miss something? Only happen in the mobile version, after I press any link in hamburger menu.

Thank you!


Solution

  • My first comment:
    You are replacing data in nav-placeholder div., which will replace the script. So, keep the script outside the that div.

        <script>
            $.get("nav.html", function(data) {
                $("#nav-placeholder").replaceWith(data);
            });
    
        </script>
    
    <div id="nav-placeholder">
    </div>
    

    About your problem:
    You are getting all the content from nav.html. So when you try to load the content from inside nav.html, it won't work as expected. So, make a copy of nav.html and name it as content.html or so. Then use content.html in both files.

    Note:
    Make sure the path is provided correctly