For my latest project, I am working on a single page application that features a dynamic navbar. The purpose of this application is for a music review site where genres like 'Pop', 'HipHop' and 'Jazz' will be showcased in the navbar. Instead of having separate HTML pages for each genre, I want to consolidate everything into one large HTML page.
Although I have the JavaScript code ready to make this happen, I need guidance on how to adjust the navbar content accordingly.
This is the snippet of my javascript file and nav bar:
I would greatly appreciate any assistance
pages: [],
show: new Event('show'),
init: function(){
app.pages = document.querySelectorAll('.page');
app.pages.forEach((pg)=>{
pg.addEventListener('show', app.pageShown);
})
document.querySelectorAll('.nav-link').forEach((link)=>{
link.addEventListener('click', app.nav);
})
history.replaceState({}, 'Home', '#home');
window.addEventListener('popstate', app.poppin);
},
nav: function(ev){
ev.preventDefault();
let currentPage = ev.target.getAttribute('data-target');
document.querySelector('.active').classList.remove('active');
document.getElementById(currentPage).classList.add('active');
console.log(currentPage)
history.pushState({}, currentPage, `#${currentPage}`);
document.getElementById(currentPage).dispatchEvent(app.show);
},
pageShown: function(ev){
console.log('Page', ev.target.id, 'just shown');
let h1 = ev.target.querySelector('h1');
h1.classList.add('big')
setTimeout((h)=>{
h.classList.remove('big');
}, 1200, h1);
},
poppin: function(ev){
console.log(location.hash, 'popstate event');
let hash = location.hash.replace('#' ,'');
document.querySelector('.active').classList.remove('active');
document.getElementById(hash).classList.add('active');
console.log(hash)
//history.pushState({}, currentPage, `#${currentPage}`);
document.getElementById(hash).dispatchEvent(app.show);
}
}
document.addEventListener('DOMContentLoaded', app.init);
NAVBAR:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="statichtmlpage.html">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link" href="pop.html">pop</a>
<a class="nav-item nav-link" href="hiphop.html">hiphop</a>
<a class="nav-item nav-link" href="jazz.html">jazz</a>
<a class="nav-item nav-link" href="#">Absolute trash</a>