Force page scroll position to top at page refresh in HTML - javascript

I am building a website which I am publishing with divs. When I refresh the page after it was scrolled to position X, then the page is loaded with the scroll position as X.
How can I force the page to be scrolled to the top on page refresh?
What I can think of is of some JS or jQuery run as onLoad() function of the page to SET the pages scroll to top. But I don't know how I could do that.
A better option would be if there is some property or something to have the page loaded with its scroll position as default (i.e. at the top) which will be kind of like page load, instead of page refresh.

For a simple plain JavaScript implementation:
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}

You can do it using the scrollTop method on DOM ready:
$(document).ready(function(){
$(this).scrollTop(0);
});

The answer here does not works for safari,
document.ready is often fired too early.
Ought to use the beforeunload event which prevent you form doing some setTimeout
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});

Again, best answer is:
window.onbeforeunload = function () {
window.scrollTo(0,0);
};
(thats for non-jQuery, look up if you are searching for the JQ method)
EDIT: a little mistake its "onbeforunload" :)
Chrome and others browsers "remember" the last scroll position befor unloading, so if you set the value to 0,0 just before the unload of your page they will remember 0,0 and won't scroll back to where the scrollbar was :)

To reset window scroll back to top, $(window).scrollTop(0) in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.
To prevent that, set the history.scrollRestoration to "manual".
//Reset scroll top
history.scrollRestoration = "manual";
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});

You can also try
$(document).ready(function(){
$(window).scrollTop(0);
});
If you want to scroll at x position than you can change the value of 0 to x.

Check the jQuery .scrollTop() function here
It would look something like
$(document).load().scrollTop(0);

The JS history API has the scrollRestoration property, which when set to manual, prevents the last scroll location on the page to be restored:
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}

Instead of location.reload(), simply use location.href = location.href. It will not scroll to the previous position as location.reload() does.
Note: This will not reload if there is any # in the URL

<script> location.hash = (location.hash) ? location.hash : " "; </script>
Put the above script in <head> tag of your html. Not sure how single page apps behave! But sure works like charm in regular pages.

The answer here(scrolling in $(document).ready) doesn't work if there is a video in the page. In that case the page is scrolled after this event is fired, overriding our work.
Best answer should be:
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});

$(document).ready(function(){
$(window).scrollTop(0);
});
did not work for me as google chrome would just scroll back down after the page finished loading.
What I used was
$(document).ready(function() {
var url = window.location.href;
console.log(url);
if( url.indexOf('#') < 0 ) {
window.location.replace(url + "#");
} else {
window.location.replace(url);
}
});
// This loads the page with a # at the end. So it will always load at the top.

I found that these CSS styles force the page to always scroll to top on reload/refresh:
html {
height: 100%;
overflow: hidden;
width: 100%;
}
body {
height: 100%;
overflow-x: hidden;
overflow-y: auto;
width: 100%;
}

This is one of the best way to do so:
<script>
$(window).on('beforeunload', function() {
$('body').hide();
$(window).scrollTop(0);
});
</script>

You can use location.replace instead of location.reload:
location.replace(location.href);
This way page will reload with scroll on top.

you can use it it your html page to
as:
history.scrollRestoration = "manual";
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});

The supercalifragilisticexpialidocious answer is:
add this at the top of your js file or script tag
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
document.body.scrollTop = 0; // For Safari

Related

After History Back, Scroll to Top

I'm using this code in my Web app to go back a page:
window.history.go(-1);
It works well, but it takes users to the same vertical location they were on the page. After going back, how can I have the TOP of the page being shown instead?
I tried:
<script>
window.history.go(-1);
window.scrollTo(0, 0); // This doesn't execute.
</script>
I don't need smooth animations or transitions. The key is just making sure the command runs after going back.
Well, after trying several things these are the only two that worked for me.
jQuery
$(window).on("pageshow", function(event) {
window.scrollTo(0, 0);
});
JavaScript
window.onpageshow = function(event) {
window.scrollTo(0, 0);
};
I hope it helps someone.
This method works on Firefox though, not in Chrome. You can refer to this question After travelling back in Firefox history, JavaScript won't run for more details.
You can use this code in first_page.html:
<script>
window.onunload = function () { };
scrollTo(0, 0);
</script>
The onunload with make sure the scrollTo(0, 0) is executed even if the back button is pressed or even if you use window.history.go(-1);
Use history.scrollRestoration:
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
}
history.back();
Profit!
scrollRestoration at MDN

Scroll down to specific position after page refresh issue

I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}

Fade page out on leaving url (as well as in on landing)

I have seen this effect here - the page fades in on load and fades out on links... I have found code snips to do this.
The code I have so far:
$(document).ready(function() {
// the body is already set to display none!
$("body").delay(500).fadeIn(500);
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(500, redirectPage);
});
function redirectPage() {
window.location = linkLocation;
}
});
... but what I can not figure out is how the page fades out and back in when you refresh the page in the OneUp theme example above???
Might it be ajax??
Check this out
http://api.jquery.com/unload/
I think it may be what you are looking for. Just make a function that fades out the page and you can call it when someone clicks away or refreshes.
This is the correct answer... Go to the link, refresh the entire page. Watch the text.
http://jsfiddle.net/xom89ne6/2/
body{
display: none;
}
$(function(){
$("body").delay(500).fadeIn(1000);
$(window).on('beforeunload', function(){
$("body").fadeOut(1000);
});
});

How to prevent links to anchors in a child div from affecting main url?

Consider the following snippet:
<div id="help"></div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var loadPage = function (){
$("#help").load("http://localhost:3000/manual.html");
}
onload=loadPage;
</script>
This exists on my main page:
http://localhost:3000/
The above code works fine and loads my manual page. But if I click a link like this in manual.html:
<a href='#introduction'>Introduction</a>
Then the page in the help div jumps to the #introduction section, however the url in my browser updates to:
http://localhost:3000/#introduction
This is pointless because the #introduction anchor only exists in manual.html, how can I prevent the links in the #help div from affecting the address bar in the browser?
Try this
$('a').click(function(e) {
e.preventDefault();
$("#help").load($(this).attr('href'));
})
By using offset and preventDefault
$('a').click(function(e) {
// Go to '#introduction'
var targetId = $(this).attr('href');
$('html, body').offset({ top: $(targetId).offset().top, left: 0 });
// this prevent 'http://localhost:3000/#introduction'
e.preventDefault();
});
See this post
I already had a function that could scroll the #help window to a heading, when you click on objects in the parent it scrolls to the relevant section in the help window:
var moveTo = function(destination){
//position of the top of the help window - does not change.
var helpWindow = $("#help").offset().top;
//difference between current scroll position and target position.
var relativeDistance = $(destination).position().top - helpWindow;
//add the distance from current position to the top to get distance to target from top
var absoluteDistance = relativeDistance+ $("#help").scrollTop();
$("#help").animate({
scrollTop: absoluteDistance
}, 1000);
}
Using e.preventDefault() I was able to use this function to do what I want.
For others heading down this path there are two other small things to consider.
Firstly, make sure you nest the .click() function inside the callback from page load, as the hyper links won't exist until the page is loaded. Secondly, You will probably want to use a child selector eg $('#help a').click() to ensure you are only altering the behaviour on links inside the child.
$("#help").load("http://localhost:3000/manual.html", function(){
$('#help a').click(function(e) {
e.preventDefault(); //suppress standard link functionality
moveTo($(this).attr('href')); //scroll to link instead.
})
});

disable address bar and back and forward button of browser

how can I disable or hide address bar and back and forward buttons in ie and firefox
i tried lots of links and solutions but non of them worked
for example for disabling back button:
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
but it seems that it goes to previous page then it returns
and i trid :
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
}
for disabling menu bar but it didnt work
what can i do
Instead of disabling the back button, try to make your page that supports users to going back. It will increase the usability of your application.
Even you can impliment it for the ajax activities also.
Don't think you can disable buttons on browser. I mean, otherwise, we'd seen it on spyware infected sites...
In terms of hiding them, I've seen banks use a full screen popup without those buttons (but hardware button on mouse or hitting backspace still works).
Not tested but you can bind to the window's hashchange event.
For example, in jQuery it very easy to do:
$(window).bind('hashchange', function(e)
{
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false; // stop event
});
The result is that the back button not changes the page when an anchor is in the url. But i agree with the first answer also (it is not a real answer i think, it is an advice).
You can also override the last entry in window.history, so user can't go back.

Categories