How Can I Prevent The Browser To Scroll To The Top On Hash Change?
I am building a web application where I need to prevent back navigation in the browser history. After searching the threads in StackOverflow I found this:
Solution 1:
I have modified code. Now its works in all modern browsers, IE8 and above
var storedHash = window.location.hash;
functionchangeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
functionchangeHashAgain() {
window.location.href += "1";
}
functionrestoreHash() {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}
if (window.addEventListener) {
window.addEventListener("hashchange", function () {
restoreHash();
}, false);
}
elseif (window.attachEvent) {
window.attachEvent("onhashchange", function () {
restoreHash();
});
}
$(window).load(function () { changeHashOnLoad(); });
Solution 2:
You are basically reloading the page every 50 ms through
window.location.href += "#";
window.location.href += "1";
Since the browser reloads when the location.href attribute changes.And you call that method again after that reload.
So the site starts to display at the top again every time.
You might generate the hash within a variable and use that for comparison i guess.
Post a Comment for "How Can I Prevent The Browser To Scroll To The Top On Hash Change?"