I'm trying to create a single webpage that replaces the content of the main div when navigation links are clicked. I've been able to implement the pushstate function to replace the div content and change the url address pretty easily. I also am able to get the content to refresh when the back/forward buttons are clicked with the popstate function. However, now I click the first link and it works fine, I click the next link and it seems to apply 2 pushstates, the 3rd click, applies 3 pushstates, etc. It seems there is a push loop occurring somewhere but not sure where it is. I am in search of some advice on how to eliminate the multiple pushstates from occurring so they aren't duplicated in my history.
HTML code:
<nav id="headerNav">
<ul>
<li><button class="navButton" id="signIn" href="./content/signIn.php" name="reply" title="SignIn">Sign In</button></li>
<li><button class="navButton" id="signUp" href="./content/registration.php" name="registration" title="Registration">Sign Up</button></li>
<li><button class="navButton" id="about" href="./content/about.php" name="settings" title="About">About</button></li>
</ul>
</nav>
<section id="mainContent">
<!-- CONTENT PAGES REPLACE HERE -->
<?php
include ('./content/start.php');
?>
</section>
Javascript
$(document).ready(function() {
if (window.history && history.pushState) {
$(".navButton").click(function(e) {
e.preventDefault();
$("#mainContent").fadeOut().load($(this).attr("href")).fadeIn();
history.pushState(null, $(this).attr("title"), $(this).attr("name"));
});
}
});
window.addEventListener('popstate', function() {
//WHEN BACK/FORWARD CLICKED CHECKS URL PATHNAME TO DETERMINE WHICH CONTENT TO PLACE IN DIV
if (location.pathname == "/index.php") {
$("#mainContent").load("./content/start.php");
} else {
$("#mainContent").load("./content" + location.pathname + ".php");
}
});
SOLVED! It was my "if" condition to test for the history API. When I removed that it eliminated the repeated history pushes. I also have my htaccess file redirecting all typed in urls to the index page that allows the pathname comparison to fire for the content. Works great but I know I'll have to address the bookmarking IF later as the site grows. For now, it functions the way I need it to so I can move forward!