I have a website where real estate properties search results are displayed like using <div>
s with just 6 displayed by default and "load more" button. When user clicks Load more button, 9 more posts displayed, etc. How it is done: div
s are hidden by default (display: none;
) and then .show
class is added to the next 9 items.
a("span.more-search-items").on("click", function(t) {
t.preventDefault();
var e = a(this).parents(".property-search");
e.find(".prop").not(".show").slice(0, 9).each(function() {
var t = a(this).attr("data-img");
a(this).css("background-image", "url(" + t + ")"), a(this).find(".main-image").attr("src", t), a(this).addClass("show")
}), 0 == e.find(".prop").not(".show").length && a("span.more-search-items").hide();
e.find(".prop.show").length
When user goes to single property and then hits back browser button, it shows the first 6 items again. I tried to implement history.pushState()
method there where URL changes for each "load more" button click:
var href = window.location.href.replace(window.location.hash, '');
var currentPage = location.hash.replace("#","");
history.pushState(null, null, href + "#" + (+currentPage + 1));
URL changes but the story is still the same - only first 6 results are being displayed when user goes back in history. Is there something I can do in this situation?
If you need to deal with History API
you need
on load more click you need to push or replace the history with something like the numbers of visible divs with hash #15 , #24
something like this
With push/replace state you need to use $(window).on('popstate' , function(){ alert(window.location.hash); })
and while user goes to single property it refresh all the page and when browser back button clicked it returns and refreshes the previous page .. so you need to check alert(window.location.hash);
when page load
Finally when you got an alert with the number from window.location.hash
you can then show the divs depending on it
Ok let me explain this for you in code
$(document).ready(function(){
alert(window.location.hash); // check the alert here
$('.load_more_button').on('click' , function(){
if(window.location.hash){
var href = window.location.href.split('#');
var currentPage = parseInt(window.location.hash);
history.pushState(null, null, href[0] + "#" + (+currentPage + 1));
}
});
$(window).on('popstate' , function(){
alert(window.location.hash); // check the alert here
});
});
You can start from here when you get the number do as you like