I created a single navbar.html and included it in all the pages of my website.j The css works fine but the javascript is unable to select elements from that navbar.
navbar.html:
<nav class="navbar">
<h1>
This is a navbar
</h1>
</nav>
index.html where it is replaced with a placeholder:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="nav-placeholder"></div>
<script src="app.js"></script>
</body>
</html>
app.js that is replacing the navbar and implementing a test function:
$(function(){
$(".nav-placeholder").load("nav.html");
});
document.querySelector('.navbar').addEventListener('click', function(){
alert('clicked');
})
You're trying to bind your event listener before the load function had inserted the data into the DOM.
Either use event delegation or move the work of binding the event listener into a callback function you pass as the second argument to the load method.