Get the vertical position of the scroll bar for a web page in pageload when the url contains an anchor

I use the jQuery scrollTop () method to get the vertical position of the scrollbar in pageload. I need to get this value after binding in url (ex url: www.domainname.com # foo). I can use the following code and it works in Firefox and IE:

ex url: www.domainname.com # foo

$(document).ready(function() {    
    if ($(this).scrollTop() > 0) {
         // then a conditional statement based on the scrollTop() value
         if ($(this).scrollTop() > $("#sidenav").height()) { ...

But in Safari and Chrome, document.ready () seems to be executed before the binding, so scrollTop () returns 0 to load the page in this script. How can I access the scrollTop () value when the page loads after binding in Chrome and Safari?

+3
source share
1 answer

, - , setTimeout, , Chrome Safari

var MAX_CHECKS = 5;             // adjust these values
var WAIT_IN_MILLISECONDS = 100; // however works best
var checks = 0;

function checkScroll() {
  if ($(this).scrollTop() > 0) {
    // then a conditional statement based on the scrollTop() value
    if ($(this).scrollTop() > $("#sidenav").height()) {
      ...
    }
  } else {
    if (++checks < MAX_CHECKS) {
      // just to make sure, you can try again
      setTimeout(checkScroll, WAIT_IN_MILLISECONDS);
    }
  }
}

$(document).ready(function() {
  // You can also throw in an if statement here to exclude
  // URLs without # signs, single out WebKit browsers, etc.
  setTimeout(checkScroll, WAIT_IN_MILLISECONDS);
  ...
});

, if ($.browser.webkit), jQuery ( ).

+4

All Articles