Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery function firing in safari but not in chrome

I have a function where I scroll to the page to the top when the page loads with document.ready(). However in Chrome this function only runs when I'm on the page and I refresh it.

If I access the page by typing the link in the address bar, the function doesn't run. If I access the page from a link from another page, it also doesn't run. The only way it runs 100% of the time in Chrome is if I'm on the page and I refresh it.

However, in Safari, the function runs 100% every single time by accessing the page from a link, typing it in the address bar, on reload.

This is my code:

jQuery(document).ready(function($) {
  if (location.hash) {               // do the test straight away
          window.scrollTo(0, 0);         // execute it straight away
          setTimeout(function() {
              window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
          }, 1);
          //location.reload();
      }
});

This actually also works in Safari without putting it in document.ready() but then again not in Chrome.

Does anybody know what causes this and if this is possible to fix? I've had this problem before and it was extremely frustrating.

like image 889
Noob17 Avatar asked Aug 06 '15 00:08

Noob17


1 Answers

Just increase the setTimeout delay time 20ms or more then 20ms, it may be because of 1ms is too short time of interval.

$(document).ready(function() {
if (location.hash) {        
          window.scrollTo(0, 0);
          setTimeout(function() {window.scrollTo(0, 0);}, 20);
}
});
like image 88
Vijay Dhanvai Avatar answered Sep 30 '22 18:09

Vijay Dhanvai