I've been doing a bit of basic web development recently and in order to implement some nice-looking navigation between 'pages' without an 'actual' page reload, I've used JavaScript to trigger transitions when the user clicks buttons on the page.
My page has got three 'content views': music, apps and stuff.
Here's my code—only 37 lines. At this stage it's perfectly manageable, but what changes could I make to help it scale up when my website gains more pages and content? All this clutter in the global scope seems a bit messy to me.
var musicContent, appsContent, stuffContent, currentlyShowingContent;
// Add event listener to initialise stuff once DOM has loaded
document.addEventListener('DOMContentLoaded', init, false);
function init() {
// Load content wrappers from DOM
musicContent = document.getElementById('music-content');
appsContent = document.getElementById('apps-content');
stuffContent = document.getElementById('stuff-content');
// Set up intitial state (showing 'music' content)
currentlyShowingContent = musicContent;
appsContent.classList.add('not-showing');
stuffContent.classList.add('not-showing');
// Add event listeners for links to each page
document.getElementById('music-button').addEventListener('click', function (){
switchContentTo(musicContent);
});
document.getElementById('apps-button').addEventListener('click', function (){
switchContentTo(appsContent);
});
document.getElementById('stuff-button').addEventListener('click', function (){
switchContentTo(stuffContent);
});
};
function switchContentTo(newContent) {
// Hide current content
currentlyShowingContent.classList.add('not-showing');
// Show new content
newContent.classList.remove('not-showing');
currentlyShowingContent = newContent;
}
Whilst I am aware that there is nothing horribly wrong with the way I have programmed this, I am wondering if there is a better way of structuring my code. If my website were to grow and I wanted to add some more 'pages', I would have to go back into my code and manually insert lines that add event listeners for each button and handle them separately. This seems like an awful faff for simply wanting to add some content.
Is this kind of code normal in web development? I've read a lot about structuring JavaScript code including using patterns such as Modules but it all seems a bit too complicated for code that is in only in charge of a single web page. I've also read quite a lot about web development in general, but books and websites never seem to address structuring JavaScript code.
Can I write this in a better way that allows me to entirely separate content from web page logic?