Reputation: 723
I have a simple javascript that I am trying to get to work but
I was able to collect the y Axis by using
var tempScrollTop = $(window).scrollTop();
but I am unable to scroll to the same position in the refreshed url.
Because there is no error showing I cant figure out what is causing my script not to work.
$(".refreshfix").click(function(e){
event.preventDefault();
var tempScrollTop = $(window).scrollTop();
var address = $(this).attr("sorttype");
// window.location.replace(address);
// window.location.href = address;
// window.location = address;
// document.location.reload(true)
window.location.assign(address);
$(window).scrollTop(tempScrollTop);
// window.scrollTo(0, tempScrollTop);
console.log(tempScrollTop)
});
I tried variations of using to use scrollTo and scrollTop as well as. I commented out some of the code that I have tried but its not working.
My best guess is that this new page that it has moved to does not has lost the variable "tempScrollTop" but I have not idea how to transport the variable to be used in the next page. I have found some reference on stackoverflow that allows me to scroll to specific position but none that gives any tips on scrolling to position on a refreshed page. Am new to JavaScript, does anyone have any ideas on this?
Thank you
Upvotes: 0
Views: 521
Reputation: 33933
When the page refreshes, it does because of window.location.assign()
, all you variables are gone in the nothingness. A new page loads.
But you can use localStorage()
to store/retreive values. That is quick and easy.
// On load, get the value if exist
var scroll_y = parseInt( localStorage.getItem("scroll_y") );
// If there is a value, scroll!
if(!isNaN(scroll_y)){
$(window).scrollTop(scroll_y);
console.log(scroll_y);
}
// On click, store the value.
$(".refreshfix").click(function(e){
event.preventDefault();
var tempScrollTop = $(window).scrollTop();
var address = $(this).attr("sorttype");
localStorage.setItem("scroll_y",tempScrollTop);
window.location.assign(address);
});
Upvotes: 2