0

I would like to include a HTML menu in a separate file using jQuery so I don't have to change all the pages every time I change something in menu. I have the following code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
    <link href="style.css" rel="stylesheet">
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>
    <script>$(".top-menu").load("menu.html");</script>

    </br>
    <div>
        Some text
        <audio autoplay><source src="some-sound.mp3" type="audio/mpeg"></audio>
    </div>
</body>
</html>

The menu is in file "menu.html":

<nav class="top-menu">
    <ul class="menu-main">
        <li><a href="pageone.html">One</a></li>
        <li><a href="pagetwo.html">Two</a></li>
        <li><a href="pagethree.html">Three</a></li>/
        <li><a href="pagefour.html">Four</a></li>
    </ul>
</nav>

But the menu doesn't show up on this page. What is wrong with the code?

  • 1
    Possible duplicate of [How to load external html into a div?](https://stackoverflow.com/questions/19370417/how-to-load-external-html-into-a-div) – StudioTime Oct 17 '17 at 14:44
  • @Jakub Raban, have we solved your problem ? Check green tick on the best answer if yes – GGO Oct 18 '17 at 07:52

3 Answers3

1

You can't call $(".top-menu") if the element <nav class="top-menu"> isn't in the same page.

Add a div with id="menu", and try to full it, like :

<body>
    <div id="menu"></div>
    </br>
    <div>
        Some text
        <audio autoplay><source src="some-sound.mp3" type="audio/mpeg"></audio>
    </div>
    <script>$("#menu").load("menu.html");</script>
</body>
GGO
  • 2,678
  • 4
  • 20
  • 42
1

I recommend you to make an element where you want to put your menu, for example:

<body>
    <div class="top-menu"></div>
    ...
</body>

Then put this at the end of your document, before closing <body> tag.

<script>$(".top-menu").load("menu.html");</script>

I would highly recommend you to use an MVC framework, where you can define layout and then single pages will be the views. That depends on you.

Patrik Krehák
  • 2,595
  • 8
  • 32
  • 62
0

You should try this way. (In you main/index.html file)

$(document).ready(function() {
   $('#anyDiv').load('some-local-path/menu.html');
 });

anyDiv may be a div element in you main.html page where you're trying to include menu.html

Make sure that you've both of the files on the same domain, otherwise you'll have to use Cross-Origin Resource Sharing

Muhammad Usman
  • 10,039
  • 22
  • 39