A simple one-page navigation script I often use looks like this:
$(document).ready(function() {
$("#coursesButton").on("click", function(e) {
e.preventDefault();
$("#mainContent").load("/snippets/courses.html");
}
$("#accountButton").on("click", function(e) {
//... etc.
}
Use as many of these blocks as you have menu items.
Basically, repeat and then /snippets/courses.html
is changed to /snippets/account.html
, etc. Keep your extra HTML files in the snippets folder (or however you'd like to arrange it).
The constant is the <div>
with an ID of #mainContent
. This way, you are simply swapping in/out the contents of that main DIV without having to keep other elements in the document when they aren't in use.
There may be a more elegant way to do this using $(this)
and matching snippet filenames to the button's ID, but the above method should work in a way that's a bit easier to understand than what you're currently doing.