Basically, I'm coding a personal website and have made a single page application with ajax so content is added to the page between the header and footer when a page in the navigation bar is clicked. I had to manually code the push state and pop state in order to get the back and forward arrows working, which they do. However, the only issue left is that when I reload the page, I get an entry not found error.
I'm very new to web dev and javascript so some of my code is a little messy. I know the reload issue has to do with the added page URL not actually existing on the server.
Here are the relevant pieces of my code:
HTML:
<nav>
<ul class='nav-bar'>
<li class='nav-item'><a id='writing'>Writing</a></li>
<li class='nav-item'><a id='editing'>Editing</a></li>
<li class='nav-item'><a id='about'>About</a></li>
<li class='nav-item'><a id='contact'>Contact</a></li>
</ul>
</nav>
Javascript
//change page on nav click
$('.nav-bar li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('id');
var file = page + '.html';
var origin = window.location.origin;
//nav color change for current page
removeActiveLinks();
$(this).parent().addClass("active");
$.ajax({
type: 'GET',
url: origin,
dataType: 'html',
success: function(response) {
$('#content').load(file);
},
error: function(error) {
console.log('There was an error', error);
}
});
window.history.pushState(file, null, '/' + page);
});
//nav for home page
$('#home').on('click', function(e) {
e.preventDefault();
removeActiveLinks();
$('#content').load('home.html')
window.history.pushState('index.html', null, '/');
});
//ensure page back functionality
window.addEventListener('popstate', function(event) {
var prevState = event.state;
$('#content').load(prevState);
removeActiveLinks();
var page_id = '#' + prevState.split('.')[0];
$(page_id).parent().addClass('active');
});
I would suggest something simpler, using simple load() (shorthand for ajax) and a the state of the history directly.
Not tested, but should work fine.
// Initial page load
$(document).ready(function(){
$("#content").load("home.html");
})
// Change page on nav click
$(".nav-bar li a, #home").on("click", function (e) {
e.preventDefault();
var file = this.id + ".html";
//nav color change for current page
$(".active").removeClass("active");
if(this.id != "home"){
$("#"+this.id).parent().addClass("active");
}
$("#content").load(file);
window.history.pushState(file, null, "/");
});
// Ensure page back functionality
window.addEventListener("popstate", function (event) {
var prevState = event.state;
$("#content").load(prevState);
var page_id = "#" + prevState.split(".")[0];
$(".active").removeClass("active");
if(page_id != "#home"){
$(page_id).parent().addClass("active");
}
});
But there is no /writing in the adress bar with this solution. If you insist on it, you will have to dive in more complex route settings on the server.