Reputation: 113
I am creating an MVC application with a simple custom tab interface displayed on the page. As a user selects each tab, I do an AJAX GET request to load new content into the tab body area. This works fine though I am looking to implement the HTML5 History API so that the browser history is updated and the user is able to return to a prior tab by clicking the browsers back button. I have built a rough prototype with the core listed below though am stuck on being able to return to the first state of the tab control. For example when I load the page. Tab one is selected. I then click tab two followed by three and four. Clicking the browser back button returns me to tab three, tab two but not tab one.
I would really appreciate any suggestions that anyone has (will tidy up the code later to be more cross browser compatible)
<div id="publicationList">
@{Html.RenderAction("DocumentsView", "Publications", new { @area = "InformationCentre", @id = @Model.selectedCategory });}
@section scripts
{
<script type="text/javascript">
$(".tabOption").click(function (e) {
e.preventDefault();
var categoryID = $(this).attr("data-categoryID");
GetCategoryPublications(categoryID);
if (history.pushState) {
history.pushState({ id: categoryID }, null, "");
}
});
function GetCategoryPublications(categoryID)
{
$.ajax({
type: 'GET',
url: '@Url.Action("DocumentsView", "Publications", new { @area = "InformationCentre" })',
async: false,
data: { id: categoryID },
success: function (data) {
$(".tabOption").removeClass("selected");
$('.tabOption[data-categoryID=' + categoryID + ']').addClass('selected');
$('#publicationList').html(data);
}
});
}
$(window).bind('popstate', function (e) {
var state = e.originalEvent.state;
if (state) {
if (state.id !== undefined) {
GetCategoryPublications(state.id);
}
}
});
</script>
}
Upvotes: 0
Views: 1143
Reputation: 113
I see what I was doing wrong now. I was not pushing the state on the initial load of the page. There is a more appropriate command for this 'replaceState':
if (history.replaceState) {
history.replaceState({ id: @Model.selectedCategory }, null, "");
}
Upvotes: 1