Results 1 to 8 of 8

Thread: [RESOLVED] Creating links in TOC?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2009
    Posts
    166

    Resolved [RESOLVED] Creating links in TOC?

    Would it take a lot of code to generate each list item in the table of contents as a link to the place it references within the document? I've got some code that makes a TOC for a document. Would the <h3> tags need ids to link to or would that be taken care of by the javascript code?


    Code:
    var tocDiv = document.getElementById("toc");	// get the id of the toc division
    	   
    var headings = document.getElementsByTagName("h3");	// get all of the <h3> headings
    		
    for (var i = 0; i , headings.length; i++) {		// process all of the <h3> headings
    alert(headings.item(i).firstChild.nodeValue);	// display what is in the ith heading (here only for example)
    var tocText = document.createTextNode(headings.item(i).firstChild.nodeValue);	// create a node of the text in the heading
    			
    tocDiv.appendChild(tocText)		// append the new paragraph to the division
    			
    var newBr = document.createElement("br");	// create a <br/> element
    			
    tocDiv.appendChild(newBr);	// append the <br/> to the division
    			
    }
    document.body.appendChild(tocDiv);	// append the division to the document body

    I found this code pasted below and wondered if this is the way to do it this? All my headings are h3 tags and I don't know what it means about the reference to Netscape. Would it really take this much coding to take what I have up above and make links out of it? I'm just looking for the most simplistic way to try to do it?
    Code:
    <HEAD>
    
    <style type="text/css">
    <!--
    #TOC {
      margin: 0px;
      display: inline;
      border-style: none;
    }
    
    #TOC a.:link {
      color:blue;text-decoration:none
    }
    #TOC a:visited {
      color:orange;text-decoration:none
    }
    #TOC a:hover {
      color:red;text-decoration:underline
    }
    #TOC a:active {
      color:green;text-decoration:underline
    }
    
    #TOC li.H1 {
      font: normal normal normal 14pt Comic Sans MS,verdana,georgia,arial;
      list-style-type: none;
      margin-left: 0px;
    }
    #TOC li.H2 {
      font: normal normal normal 12pt Comic Sans MS,verdana,georgia,arial;
      list-style-type: none;
      line-height:16px;
      margin-left: 10px;
    }
    #TOC li.H3 {
      font: normal normal normal 10pt verdana,Comic Sans MS,georgia,arial;
      list-style-type: none;
      line-height:16px;
      margin-left: 20px;
    }
    #TOC li.H4 {
      font: italic normal normal 10pt verdana,Comic Sans MS,georgia,arial;
      list-style-type: none;
      line-height:16px;
      margin-left: 30px;
    }
    #TOC li.H5 {
      font: italic normal normal 10pt verdana,Comic Sans MS,georgia,arial;
      list-style-type: none;
      line-height:16px;
      margin-left: 40px;
    }
    #TOC li.H6 {
      font: italic normal normal 10pt verdana,Comic Sans MS,georgia,arial;
      list-style-type: none;
      line-height:16px;
      margin-left: 50px;
    }
    -->
    </style>
    
    <script type="text/javascript">
    
    
    var stateTOC = 'ON';
    
    function toggleTOC() {
      if (stateTOC == 'ON') {
        stateTOC = 'OFF'
        document.getElementById('TOC').style.display = "none";
      }
      else {
        stateTOC = 'ON'
        document.getElementById('TOC').style.display = "inline";
      }
    }
    
    function buildTOC() {
      /***************************************/
      /* Get desired tags and store in array */
      /***************************************/
      
      validTagList = '. H1 H2 H3 H4 H5 H6 .';
    
      // Get list of all tags & store in array.
      // DOM Level 1 Standard */
    
      if (document.body.childNodes) {
        // alert('DOM Standard');
        allTags = getObjects();
      }
      // Microsoft proprietry intermediate DOM
      else if (document.all) {
        // alert('document.all');
        allTags = document.all;
      }
      // Netscape proprietry intermediate DOM
      else if (document.layers) {
        // alert('document.layers');
        alert('Netscape layers? What to do, what to do ....');
      }
    
      var tagDetail = new Array(1);
      j = 0;
      aNum = 0;
      for(i = 0; i < allTags.length; i++) {
        if (validTagList.indexOf(' '+allTags[i].tagName+' ') > 0) {
          // Add an anchor as a child to the tag so that toc link to it
          aNum = aNum + 1;
          var aNode = document.createElement("A");
          aNode.id = 'Z'+aNum;
          allTags[i].appendChild(aNode);
    
          // Keep relevant data fron the tag to use in toc separated by "|".
          // ....the name of the tag (eg. H3)
          tagDetail[j] = allTags[i].tagName + "|";
    
          // ....the anchor number we have assigned
          tagDetail[j] = tagDetail[j]+aNum + "|";
    
          // ....the text of the tag
            if (allTags[i].childNodes.length > 0) {
              tagDetail[j] = tagDetail[j]+allTags[i].childNodes[0].nodeValue
          }
          ;
          j = j + 1;
        }
      }
    
      /***************************************/
      /*Build toc                            */
      /***************************************/
      var ulNode = document.createElement("UL");
      tocId = document.getElementById('TOC');
      tocId.appendChild(ulNode);
    
      for(i = 0; i < tagDetail.length; i++) {
        thisDetail = tagDetail[i].split("|");
    
        var liNode = document.createElement("LI");
        liNode.className = thisDetail[0];
        ulNode.appendChild(liNode);
    
        var aNode = document.createElement("A");
        aNode.className = thisDetail[0];
        aNode.href = '#Z'+thisDetail[1];
        liNode.appendChild(aNode);
        aNode.innerHTML = thisDetail[2];
    
        // alert('i='+i + ' tagName='+aNode.tagName + ' href='+aNode.href + ' className='+aNode.className + ' text='+aNode.innerText);
    
      }
    }
    
    function getObjects() {
      var obj = new Array(1);
      j = 0;
      obj[j] = document.documentElement;
      traverse( document.documentElement );
    
      function traverse(node) {
        obj[j] = node;
        j = j + 1;
        if (node.childNodes != null) {
          for (var i=0; i < node.childNodes.length; i++) {
            traverse(node.childNodes.item(i));
          }
        }
      }
      return obj;
    }
    //-->
    </script>
    </HEAD>
    
    <!-- Optional anchor for return to TOC -->
    <a id=tocPos></a>
    
    <!-- Optional access key (ALT-t) to return to TOC -->
    <a href="#tocPos" title="AccessKey: t" accesskey="t"></a>
    
    <!-- Optional button to toggle TOC on/off -->
    <input
       type = "button"
       value = "Table of Contents"
       onclick = "toggleTOC()">
    
    <!-- Required div to position TOC -->
    <div id=TOC>
    </div>
    
    <h1>header 1</h1>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    
    <h2>header 1.1</h2>
    <h3>header 1.1.1</h3>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    
    <h1>header 2</h1>
    <h2>header 2.1</h2>
    <h3>header 2.1.1</h3>
    <h4>header 2.1.1.1</h4>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    
    <h4>header 2.1.1.2</h4>
    <p>paragraph 4</p>
    
    <h3>header 2.1.2</h3>
    <h4>header 2.1.2.1</h4>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    
    <h1>header 3</h1>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore</p>
    
    <p><center>
    <font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
    by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
    </center><p>

  2. #2
    Addicted Member
    Join Date
    Sep 2005
    Posts
    150

    Re: Creating links in TOC?

    You have asked multiple questions here and I will attempt to answer them as much as I can.
    Would it take a lot of code to generate each list item in the table of contents as a link to the place it references within the document?
    Your code is so much because they have defined all headings (from h1 - h6). In your case, you said you are using only H3, so you can delete the rest to reduce the length of your code.

    Would the <h3> tags need ids to link to or would that be taken care of by the javascript code?
    I could see that the TOC was referenced by both the JavaScript and CSS. In that case, H3 would need an id to link to and the JavaScript will also apply.

    ...what it means about the reference to Netscape.
    If you are referring to the line below and the few lines that followed it in the program,
    Code:
    // Netscape proprietry intermediate DOM
    it means what to do if the user's browser is Netscape navigator. The code above that in the program is for Microsoft Internet explorer.

    Hope this helps.
    Menre

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    May 2009
    Posts
    166

    Re: Creating links in TOC?

    Yes, it helps. Thanks. I'll start by giving each paragraph an anchor tag.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    May 2009
    Posts
    166

    Re: Creating links in TOC?

    Is it possible to name each <h3> tag using a command like
    Code:
    document.getElementByTagName("h3")[0].setAttribute("id","h31");
    Since I'm trying to make links I need to put the id in an <a> tag but I'm not sure how to get this added to the <h3>, like this statement: document.h3.createElement('a')

    There must be some way to do it so that it that it can be named by the loop since the variable "i" increase each time through and the links are generated from the loop.

    Does this look like I'm heading in the right direction?

    Code:
    document.getElementByTagName("h3")[0].setAttribute("id","h3.item(i)");
    Last edited by Blue1974; Nov 23rd, 2009 at 10:46 PM.

  5. #5
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Creating links in TOC?

    err, you could try:

    Code:
    document.getElementByTagName("h3")[0].setAttribute("id","h3" + i);
    but I have no idea if that would work.

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    May 2009
    Posts
    166

    Re: Creating links in TOC?

    Thanks for the suggestion but I think I needed to use something called a toString method. I don't fully understand the way this all works but just following along with directions.

    I'm at the point where I get the window alert about the first heading when I click on the button it doesn't print the heading within the toc.div to form the table of contents.

    I'm guessing there must be something wrong with my line:
    Code:
    divE1.appendChild(aElem);
    Any suggestions on why it doesn't append or what I'm missing?


    Code:
    var divEl = document.getElementById("toc_div");	// get the id of the toc division
    	   
    var headings = document.getElementsByTagName("h3");	// get all of the <h3> headings
    		
    for (var i = 0; i < headings.length; i++) {		// process all of the <h3> headings
    alert(headings.item(i).firstChild.nodeValue);	// display what is in the ith heading (here only for example)
    var tocText = document.createTextNode(headings.item(i).firstChild.nodeValue);	// create a node of the text in the heading
    			
    headings.item(i).setAttribute("id", i.toString());
    			
    var aElem = document.createElement('a');	//Create the new <a>
    			
    aElem.href="toc.htmll";		
    			
    aElem.href = "#" + i.toString();  
    		
    aElem.appendChild(tocText) 	// append text node to the <a> element
    			
    divEl.appendChild(aElem);	//Append the new link to the existing <div>
    			
    var newBr = document.createElement("br");	// create a <br/> element
    divEl.appendChild(newBr);	// append the <br/> to the division
    			
    }
    Last edited by Blue1974; Nov 25th, 2009 at 05:53 PM.

  7. #7
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Creating links in TOC?

    I am getting the appropriate results (I think) with the following code...
    Code:
    <html>
    <body>
    <script>
    window.onload = function(){
    var divEl = document.getElementById("toc_div");	// get the id of the toc division
    	   
    var headings = document.getElementsByTagName("h3");	// get all of the <h3> headings
    		
    for (var i = 0; i < headings.length; i++) {		// process all of the <h3> headings
    alert(headings.item(i).firstChild.nodeValue);	// display what is in the ith heading (here only for example)
    var tocText = document.createTextNode(headings.item(i).firstChild.nodeValue);	// create a node of the text in the heading
    			
    headings.item(i).setAttribute("id", i.toString());
    			
    var aElem = document.createElement('a');	//Create the new <a>
    			
    aElem.href="exercise4_2.html";		// you willl need to change this to link to an appropriate place in your page
    			
    aElem.href = "#" + i.toString();  
    		
    aElem.appendChild(tocText) 	// append text node to the <a> element
    			
    divEl.appendChild(aElem);	//Append the new link to the existing <div>
    			
    var newBr = document.createElement("br");	// create a <br/> element
    divEl.appendChild(newBr);	// append the <br/> to the division
    			
    }
    }
    </script>
    
    <div id="toc_div">
    
    </div>
    
    <h3>blah1</h3>
    <h3>blah2</h3>
    </body>
    </html>

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    May 2009
    Posts
    166

    Re: Creating links in TOC?

    SambaNeko, I got it!!!! Thanks to your assistance. I was thrilled to actually see this thing functioning. Thank you.

Posting Permissions

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



Click Here to Expand Forum to Full Width