0

I am trying to refactor the menu navigation. I want to add it into a single html file. example: menu.html will contain :

<div class="menu-toggle" id="menuToggle">
    <span></span>
</div>
other divs aswell

For each page I want to inject this html code. (to increase code reuse). using other html page:

<div id='menu=left'></div>

I have in the main.js:

(function ($) {
    "use strict";
    function menu() {
        "use strict";
        $("#menuToggle").on("click", function () {
            $(".header-left").toggleClass("open");
            $(".main").toggleClass("open");
        });
        $(".cross").on("click", function () {
            $(".header-left").removeClass("open"); 
        });
        $(".nav-link").on("click", function () {
            $(".header-left").removeClass("open");
        });
    }

    $(”#menu-left”).load(“assets/html/menu.html”);

    $(document).on("ready", function () {
        "use strict";
        menu();
    });

})(jQuery);

The output :

The menu appears. I can see the menu button but the toggle functionality does not work anymore. I tried different things but can't seem to work it out.

How can I solve this ?

Thank you

  • You need to use delegated event handlers as you're adding the menu HTML dynamically after the page loads. See the duplicate for more information. – Rory McCrossan Jun 30 '21 at 10:15
  • Also note that while using `load()` does increase code reuse, it means more server requests being made, and potentially more hosting cost and worse server performance. I'd strongly suggest you use server side includes instead of client side ones. – Rory McCrossan Jun 30 '21 at 10:16
  • You'll also get a FOUC as your page loads, displays, then there's a delay as the menu loads separately – freedomn-m Jun 30 '21 at 10:22
  • @RoryMcCrossan I am not sure i understand what i have to do in order to fix this ? Am i supposed to add the content before the page loads ? – Roy Mustang Jun 30 '21 at 10:28

0 Answers0