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?

2
  • 1
    Possible duplicate of How to load external html into a div? Commented Oct 17, 2017 at 14:44
  • @Jakub Raban, have we solved your problem ? Check green tick on the best answer if yes Commented Oct 18, 2017 at 7:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.