Faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 6 people (100%) answered Yes
Recently 6 of 6 people (100%) answered Yes

Entry

How can I dynamically generate a list of anchors in the document and place it at the top of the document?
How can I dynamically generate a list of anchors in the document and place it at the top of the document?

Jul 2nd, 2001 02:41
Martin Honnen,


You run a function onload which collects the document.anchors[i].name 
entries. You place the toc in a div via innerHTML in NN6 and IE4+ and 
rewrite the div in NN4 and move the content down as necessary. The 
following is an example which randomly generates some content with 
anchors an then writes the toc. The example works with IE4+, NN4 and 
NN6.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
generated toc
</title>
<script type="text/javascript">
if (document.layers) {
  var css = '';
  css += '<style type="text/css">';
  css += '#toc { position: absolute; visibility: hidden; }';
  css += '#content { position: absolute; }';
  css += '<\/style>';
  document.write(css);
}
function makeToc () {
  var html = 'TOC:<ol>';
  if (document.layers)
    var doc = document.content.document;
  else
    var doc = window.document;
  for (var i = 0; i < doc.anchors.length; i++)
    html += '<li><a href="#' + doc.anchors[i].name + '">anchor ' + i + 
'<\/a><\/li>';
  html += '<\/ol>';
  if (document.layers) {
    document.toc.document.open();
    document.toc.document.write(html);
    document.toc.document.close();
    document.content.top = document.toc.pageY + 
document.toc.document.height;
    document.toc.visibility = 'show';
  }
  else if (document.all)
    document.all.toc.innerHTML = html;
  else if (document.getElementById)
    document.getElementById('toc').innerHTML = html;
}
</script>
</head>
<body onload="makeToc();">
<div id="toc"></div>
<div id="content">
Example content:<br />
<script type="text/javascript">
var n = Math.floor (Math.random() * 15) + 1;
var html = '';
for (var i = 0; i < n; i++) {
  html += '<a name="anchor' + i + '">Kibology ' + i + '<\/a><br \/>';
  html += '<ul>';
  for (var j = 0; j < 5; j++)
    html += '<li>Kibology ' + i + ', ' + j + '<\/li>';
  html += '<\/ul>';
}
document.write(html);
</script>
</div>
</body>
</html>