Reputation: 12512
I am submitting some data with jQuery
via ajax
, and on success I am refreshing page with
document.location.reload(true);
Is there any way to prevent page scrolling back top the top. I did a bit of research and it seems possible to fool Chrome. I also came across the following function, but not really sure where to place it in order for it to work.
if (window.location.hash) {
//bind to scroll function
$(document).scroll( function() {
var hash = window.location.hash
var hashName = hash.substring(1, hash.length);
var element;
//if element has this id then scroll to it
if ($(hash).length != 0) {
element = $(hash);
}
//catch cases of links that use anchor name
else if ($('a[name="' + hashName + '"]').length != 0)
{
//just use the first one in case there are multiples
element = $('a[name="' + hashName + '"]:first');
}
//if we have a target then go to it
if (element != undefined) {
window.scrollTo(0, element.position().top);
}
//unbind the scroll event
$(document).unbind("scroll");
});
}
Since I'm refreshing this page, after submitting via a click on an element, shall i attach it somehow to .click
event?
Upvotes: 0
Views: 7308
Reputation: 615
We can use cookie to do it.
Before you reload the page, add cookie for last position of scrollTop:
$.cookie('last-scroll-top', $(window).scrollTop());
document.location.reload(true);
And when the page reload, we read the cookie, scroll and delete cookie:
var lastScrollTop = $.cookie('last-scroll-top');
if (lastScrollTop) {
$(window).scrollTop(lastScrollTop);
$.removeCookie('last-scroll-top');
}
Upvotes: 1
Reputation: 491
Solution:
In your AJAX success
add/adjust the following:
window.location.hash = "#sp" + $(window).scrollTop();;
window.location.reload(true);
Then in your document ready
or onload
:
if (window.location.hash) {
var hash = window.location.hash;
var pos = hash.substring(3, hash.length); //3 is used to remove "#sp" from hash name
if(!isNaN(pos))
window.scrollTo(0, pos);
}
Disclaimer: If you have valid reason to reload the entire page and not just a subsection of it in a div, the solution will work for you.
Upvotes: 0