Reputation: 345
I am working with AJAX content. Basically a bunch of products are on one page and when you click a product it currently goes to the product without having to reload the page at all. The product UPC is appended as a hash. Problem is that when a user clicks the back button, it doesn't work. A user currently has to rely on breadcrumbs to go back.
My solution was to use a window on hash change function, which works but obviously forces the page to reload when going forward. Kind of defeats the purpose of AJAX. Is there a better way to navigate to the last item on the page if a user clicks the back button by grabbing its hash value rather than doing what I am currently using below?
$(window).on('hashchange', function() {
var hash = window.location.hash;
var fullURL = window.location.href = "http://www.test.com/product-categories/test.php" + hash;
if (fullURL) {
location.reload();
}
});
Upvotes: 0
Views: 577
Reputation: 2228
Here is how you can do it with History API
function loadProduct(productid, reload){
$.ajax({
...
...
data: {productId : productid},
success:function(){
if(!reload) {
History.pushState('productName', { productId : productid }, '#' + productId)
}
}
})
}
$(product).on('click', function(){
loadProduct( productId , true )
});
$(window).on('popstate', function(){
loadProduct( e.state.productId, false );
});
This way you will store product id each time user clicks on a product. and when they go back & forth, it will get the stored product id and will reload it
Upvotes: 1