I wanna use the same navbar and footer across multiple pages, using the JQuery, as we can see here. However, I want a responsive navbar (see the hamburger menu at the corner). So, to do that, I had to load these tags from files. Unfortunately, the script doesn't work anymore. How can I fix it?
[EDIT] Everything works fine by replacing <div id="nav-placeholder"></div>
with the content of nav.html, but I would like to keep the code distributed. The console returns the following error:
Uncaught TypeError: toggleButton is null
<anonymous> file:///home/myProject/script.js:3
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>dummy website</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div id="nav-placeholder"></div>
</header>
<main>
<p>home content</p>
</main>
<footer>
<div id="footer-placeholder"></div>
</footer>
<script src="script.js"></script>
</body>
</html>
nav.html
<p>logo</p>
<div class="menu" id="toggleButton">
<div class="menu-line"></div>
<div class="menu-line"></div>
<div class="menu-line"></div>
</div>
<nav class="nav-links" id="nav-list">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
footer.html
<p>footer content</p>
style.css
*{
box-sizing: border-box;
padding: 0;
margin: 0;
color: white;
}
header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
background-color: green;
}
.nav-links {
list-style: none;
}
.nav-links li {
display: inline-block;
text-align: center;
padding-right: 5px;
}
.menu {
display: none;
cursor: pointer;
}
.menu-line {
background-color: white;
width: 21px;
height: 2px;
margin-top: 5px;
}
main {
height: 200px;
}
main p{
color: black;
}
footer {
background-color: red;
}
@media all and (max-width: 480px){
.menu {
display: block;
}
.nav-links {
display: none;
width: 100%;
}
.active {
display: flex;
}
.nav-links ul{
justify-content: center;
width: 100%;
}
.nav-links li {
display: block;
border-top: 1px solid white;
padding: 5px 0 5px 0;
}
}
script.js
const toggleButton = document.getElementById('toggleButton');
const navList = document.getElementById('nav-list');
toggleButton.addEventListener('click', () => {
navList.classList.toggle('active');
});
$(function(){
$("#nav-placeholder").load("nav.html");
$("#footer-placeholder").load("footer.html");
});