BACKGROUND: I've got a page with the markup shown below. I'm using jQuery's .load() method to replace the contents of div.content-container with this code:
$(document).on('click', 'button#page2', function() {
$("div.content-container").load("page2.html");
});
QUESTION: The method works, but I'd like to append the URL with a hash, i.e. #page2, which would allow back button functionality. Is there a way to add this feature to a site based entirely on HTML and jQuery .load()
?
I've looked at Ben Alman's BBQ plugin, but as someone new to asynchronous content and a non-expert in jQuery, I'm having trouble figuring out how to implement it in my project.
HTML of main page:
<head>
<!--scripts & styles-->
</head>
<body>
<button id="page2">Page 2</button>
<button id="page3">Page 3</button>
<div class="content-container">
<!--content is loaded here-->
</div>
</body>
page2.html (and later pages) are not full HTML documents:
<p>Here's some content from the second page.</p>
AFAIK, there is no way to do this withing pure jQuery. You want to manipulate the browser history to add routing to your application, and to do this you require either a jQuery plugin, or directly with the native APIs of the browser: listening to the hashchange
event and/or the HTML5 History API.
Quick and dirty toy example to "clear" your div
:
$(document).on('click', 'button#page2', function() {
$("div.content-container").load("page2.html");
location.hash = '#page2';
});
$(window).on('hashchange', function() {
if (location.hash === '') {
$("div.content-container").html('');
}
});