Auto-scroll to top of page

Description

The home page for one of our sites was loading a lot of content into various containers, much of which was created on the fly by vtl's.  As a result, we found that when the page was finished loading, the viewport would not be at the top of the page, especially when we viewed the site on an iPad.    This only occurred when the page was first loaded:  once the browser cached it, the bug did not recur.  So we added the following code to header.vtl and all was well.

Link: http://www.immobaker.com

Code

## Fix scrolling bug:  because parts of the page load asynchronously, we can end up way down the page without meaning to.
## But only if we haven't been to this page before.

## NOTE:  For all news articles, the URL that goes into the clickstream is "/news/news.detail.html".  Therefore as far as this script is concerned, if you've seen one then you've seen 'em all.  Should be okay because scrolling bug isn't really an issue for news articles.

#set($pages = $session.getAttribute("clickstream").clickstreamRequests)
 
#set($visitCount = 0)
#foreach($page in $pages)
    #if($page.requestURI==$VTLSERVLET_URI)
         #set($visitCount = $visitCount + 1)
         #if($visitCount>1)
          #break
         #end
    #end
#end
 
## If they have not been to this page before in this session, then load the JavaScript that will scroll the page to the right place
#if($visitCount<=1) ## This is the first visit to this page in this session
  <script>
    $(document).ready(function(){
      if (window.location.hash=="") { ## Take them to the top of the page but only if they haven't entered an internal anchor
        window.scrollTo(0, 0);
      } else {
        $(document.body).scrollTop($(window.location.hash).offset().top);
      }
    });
  </script>
#end