SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get scroll value and then return to it on click

    I want to...

    (1) Get the current browser scroll position/value when clicking this:
    <a href="#menu">MENU</a>

    (2) Return to the last stored scroll position when click this:
    <a href="#top">RETURN TO CONTENT</a>
    ...with #top being a non-JS fallback

    I can do everything to complete this, it's just the getting and setting of the browser scroll value I could do with some help on.

    ...and most importantly to do this without jQuery (or any other library).

    I also want it to be completely cross-browser compatible.

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Portsmouth UK
    Posts
    1,499
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
     <div style="height:300px;" ></div>
     <a href="#menu">MENU</a>
     <div style="height:300px;" ></div>
     <a href="#menu">MENU</a>
     <div style="height:1300px;" ></div>
     <a href="#top">RETURN TO CONTENT</a>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function zxcScrollTo(o){
     var oop=zxcScrollTo,as=document.getElementsByTagName('A'),z0=0;
     for (;z0<as.length;z0++){
      if (as[z0].href&&as[z0].href.indexOf(o.AnchorHREF)>0){
       as[z0].onclick=function(){
        oop.lft=window.innerHeight?window.pageXOffset:document.documentElement.clientHeight?document.documentElement.scrollLeft:document.body.scrollLeft;
        oop.top=window.innerHeight?window.pageYOffset:document.documentElement.clientHeight?document.documentElement.scrollTop:document.body.scrollTop;
        return false;
       }
      }
      if (as[z0].href&&as[z0].href.indexOf(o.LinkHREF)>0){
       as[z0].onclick=function(){ window.scrollTo(oop.lft,oop.top); return false; }
      }
     }
     oop.top=0;
     oop.lft=0;
    }
    
    zxcScrollTo({
     AnchorHREF:'#menu',
     LinkHREF:'#top'
    });
    /*]]>*/
    </script>
    </body>
    
    </html>
    I can add an animated scroll if required


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •