Scroll to anchor

Posted by ZyX on Stack Overflow See other posts from Stack Overflow or by ZyX
Published on 2010-04-14T04:39:06Z Indexed on 2010/04/14 4:43 UTC
Read the original article Hit count: 349

Filed under:
|
|

I have the following userjs which is intended to remove anchor part of the URL but still jump to it:

// ==UserScript==
// @name PurgeAnchor
// @include *
// ==/UserScript==
(function() {
 var reg=/^(.*)\#(.*)$/;
 var match=reg.exec(location);
 function ObjectPosition(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
 }
 if(match) {
    document.location.replace(match[1]);
    sessionStorage.setItem("anchor", match[2]);
 }
 window.addEventListener("load", (function() {
         var anchor=sessionStorage.getItem("anchor");
         if(anchor!==null) {
             var obj=document.getElementById(anchor);
             if(obj===null) {
                 obj=document.getElementsByName(anchor)[0];
             }
             var pos=0;
             if(obj!==null) {
                 pos=ObjectPosition(obj);
                 window.scrollTo(0, pos);
             }
             sessionStorage.removeItem("anchor");
         }
     }), false);
 })()

The problem is that if I have an empty <a> tag with the name set, it fails to jump. obj.scrollIntoView() also fails. Opera-10.52_pre6306, Gentoo.

© Stack Overflow or respective owner

Related posts about opera

Related posts about JavaScript