0

I am trying to force my website to scroll to the top when a page is reloaded and it is working everywhere except iOS which doesn't support beforeunload, I was wondering if there are any other events that are triggered when a page is refreshed.


Solution for All other browsers

$(window).on('beforeunload', function(){
  $(window).scrollTop(0);
});


What I have tried for iOS but no luck

$(window).on('pageshow', function(){
    $(window).scrollTop(0);
});

$(window).on('pageshow', function(){
        $(window).scrollTop(0);
});

$(window).on('popstate', function(){
    $(window).scrollTop(0);
});


Threads I Have Checked

Alternative for jQuery beforeunload event handler on mobile devices

Is the onbeforeunload event not supported on iPhone?

Is there an alternative method to use onbeforeunload in mobile safari?

window.onbeforeunload not working on the iPad?

oznomal
  • 439
  • 2
  • 8
  • 22

1 Answers1

0

The beforeunload event is fired when the window, the document and its resources are about to be unloaded.

So it's like you try to make the page scroll to the top... And then, let the page refresh occur.

What about to make it scroll to the top after that refresh? As the first thing to execute...
The plain JavaScript scrollTop property should do at the very begining of your script tag... When the page loads.

window.scrollTop = 0;

But that will ensure the page loads at its top on any load... A load from another page too. If you want the scrollTop to occur only on "self reload", try this:

// Retreive the previous pageName
var previousPageName = localStorage.getItem("pageName");

// Give a unique name to the actual page
var pageName = "About Us";

// Then store it for a future load
localStorage.setItem("pageName", pagename);

// Now check if the previous pageName was the same as now
// If so, then scroll to top
if(pageName == previousPageName){
  window.scrollTop = 0;
}
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64