User:Pasixxxx/TOCLinker

From Wikipedia, the free encyclopedia

Javascript code that helps to navigate in long articles. Code tries to insert links to the table of contents after appropriate headings, so that user can navigate to TOC by clicking a link, and doesn't have to scroll backwards to get to the toc, what I think is silly.

Below is an example of what the code does. Links under the headings will be generated dynamically by the code when opening a new page.

Contents

[edit] Heading1

Table of contents

When I started reading and editing Wikipedia, I didn't pay attention to the TOC at the start of the articles, I just started browsing the artice by scrolling down the page, and when I wanted to navigate to another section, I scrolled upwards, I think this what most users do. After few months, I started thinking, this is stupid, I would like to navigate by clicking not scrolling.

[edit] Heading2

Table of contents

Links to the TOC have proven to be usefull at my usage. I would like to see similar feature maybe as option in Settings, or maybe as a default.

[edit] Heading3

Table of contents

Maybe there already is a option in Wiki, but I didn't find it. It was interesting to develope this script.

[edit] Heading4

Table of contents

[edit] Code

   //Inserts links to toc if conditions are met. incubator:user:Pasixxxx
   
 function MyHtmlFrag(doc)
 {
     var sm,txt,a;
 
     this.ce=doc.createElement("center");
     sm=doc.createElement("small");
     a=doc.createElement("a");
     a.setAttribute("href","#toc");
     txt=doc.createTextNode("Table of contents");//Change this to appropriate language
 
     this.ce.appendChild(sm);
     sm.appendChild(a);
     a.appendChild(txt);
 
     return this.ce
 }
 
 function insertLinks(tg,doc)
 {
      var el,coll;
      var i;
 
      coll=doc.getElementsByTagName(tg);
        
      for(i=0;i<coll.length;i++)
      {
          el=coll.item(i);
        
          if(el.parentNode.tagName.toLowerCase()!="div") continue;
          if(el.parentNode.id!="bodyContent") continue; 
          if(el.id=="siteSub") continue;
 
          el.parentNode.insertBefore(new MyHtmlFrag(doc),el.nextSibling);
      }
 }
 
 function insertLinksToTOC()
 {
     var doc=window.document;
 
     if(doc.getElementById("toc")==undefined) return;           
 
     insertLinks("h2",doc);
     insertLinks("h3",doc);
     insertLinks("h4",doc);
 }
 
 addOnloadHook(insertLinksToTOC);