After History Back, Scroll to Top - javascript

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

Related

Add-on or "trick" to scroll directly to bottom of a auto-loading page

I would like to know, if there is a possibility for a user to instead of scrolling all the time there is a possibility to load directly the whole page (not an "auto-scrolling add-on).
I found this function here: ...infinite auto-scroll to bottom of page
function scrollToBottom(){
bottom = document.body.scrollHeight;
current = window.innerHeight+ document.body.scrollTop;
if((bottom-current) >0){
window.scrollTo(0, bottom);
setTimeout ( 'scrollToBottom()', 1000 );
}
};
scrollToBottom();
I ran it in my console and it appears to work. It looks like it could use a little work as the timer may never stop. Hope it helps.

Disable browser back action using jquery

I am developing an online testing app and it is required that during the test, users cannot be allowed to refresh page neither go back until the test is ended. I have successfully been able to disable refresh action in jquery through all means possible (to the best of my knowledge) using the following code:
$(window).bind({
beforeunload: function(ev) {
ev.preventDefault();
},
unload: function(ev) {
ev.preventDefault();
}
});
But I have been having troubles disabling the back action on all browsers, the best solution I got on SO conflicts with the code I have above, it is given below:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
//alert("Reloaded");
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload forthis.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
The solution above suits my purpose in disabling the back button but conflicts with the page refresh prevention handler above.
I am out of ideas on what to do and I have also searched a long time for a solution to this but found none yet. Any help would be greatly appreciated, even if it takes a totally different approach to solving the problem, I wouldn't mind at all.
Thanks everyone
UPDATE
I never realized that doing things this way breaks a lot of ethical rules, anyway, I've thought about it and figured out something else to do when if the page is refreshed or back button pressed (either using keyboard or the browser controls). I want to redirect to a url which will end the current exam session. I believe that's possible, hence I think the solution I seek is to get the best way to achieve this. Redirecting to another url if back button or refresh button is pressed (both using the browser controls and the keyboard).
I have tried many options but none worked except this-
//Diable Browser back in all Browsers
if (history.pushState != undefined) {
history.pushState(null, null, location.href);
}
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
With regards to the update I posted in my question, I have been able to solve my problem. Here's what I did (just modifying my existing code a little and removing the window.onload listener I had initially):
$(window).bind({
beforeunload: function(ev) {
window.location.replace("my_url_goes_in_here");
},
unload: function(ev) {
window.location.replace("my_url_goes_in_here");
}
});
This construct works for both page refresh and back actions done in anyway (either using keyboard or browser controls for the any of them).
However, I've not yet tested in any other browser other than firefox 47.0, but I'm glad it's working for now all the same.
Thanks for all your comments, they were extremely helpful
Using javascript if you have two pages page1 and page2 and (page1 redirect to page2) and you want to restrict the user from getting back to page1, just put this code at page1.
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function disableBack() {
window.history.forward()
}
window.onload = disableBack();
window.onpageshow = function (evt) {
if (evt.persisted)
disableBack()
}
});
</script>

How to get javascript Timer to stop when not viewing tab/window

I am running a page with a timer that I'm using to run in a iframe of a page so that I know that someone was on there actually with window in focus paying attention to screen and if leave have the timer pause until back viewing the window or in focus.
I have 4 timer files: timer.css timer.js timer.php & timerb.js
I believe I would execute it in the following file and code, but that is where I am stuck as don't know what or where to add it for sure and no luck yet and why here asking so please take a look and let me know if you can help.
File: timer.js
function adTimer() {
timer++;
if(timer == fulltimer) {
var show="Click "+key;
$("#buttons").fadeIn();
$("#timer").html(show);
}
else {
setTimeout(adTimer, 1000);
}
$("#bar").width((timer/fulltimer)*200);
}
This could be enough for you:
$(window).blur(function(){
//your code for inactive
});
$(window).focus(function(){
//your code for active
});
or non jQuery solution (https://stackoverflow.com/a/1760283)
window.onblur = function () {
//your code for inactive
};
window.onfocus = function () {
//your code for active
};
if not try Page Visibility API (answer already here https://stackoverflow.com/a/1060034)
Just wondering why all that implementation if JQuery already provide a timeout. did you try to use set Timeout.
http://www.sitepoint.com/settimeout-example/

Scrolling content right to left Javascript

I have a page with a horizontal width of 4000px
How would i go about creating an event that starts as soon as the page loads and cycles from the far right to left of the page? I want to show all the content and get the user back to the start if you get me
Ideally coded in javascript but will accept CSS3 (if it can be done)
Thanks Guys,
DIM3NSION
Based on your responses i have tried to get this working, but with no avail.
Help much appreciated
<script type='text/javascript'>
$(document).ready(function(){
function start(){
document.body.scrollTo(4000, 0);
var x=4000;
var t= setInterval(function(){ x-=50
if (x<=0){ clearInterval(t); document.body.scrollTo(0,0); return; } document.body.scrollTo(x, 0); }, 20) }
});
</script>
The jQuery scrollTo plugin does exactly what you need. See it in action. Combined with the setTimeout or setInterval function, you could easily achieve your goal.
I'm not sure if this would work for an entire page, but it could be slicker than using the built in browser scrollbars, and easier to set up, to boot: http://logicbox.net/jquery/simplyscroll/
There's probably some errors in this code, since I'm typing it on my phone, but something like this should work. Just stick it in a window.onload function.
function start(){
window.scrollTo(4000, 0);
var x=4000;
var t = setInterval(function(){
x-=50; // or whatever
if (x<=0){
clearInterval(t);
window.scrollTo(0,0);
return;
}
window.scrollTo(x, 0);
}, 20)
}

Force page scroll position to top at page refresh in HTML

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

Categories