2022.2

Table Of Contents
Step 2: Creating a placeholder for the TOC
CreateoneextraPrintsectiontoputtheTableOfContentsin.
Insidetheextrasection,insertanArticleelement(see"Insertinganelement"onpage173).
GivetheelementanID,forexample:toc-content.ThiselementistheplaceholderfortheTOC.
Step 3: Inserting the Post Pagination script
InsertaPostPaginationscript(see"AddingaPostPaginationScript"onthepreviouspage).
Double-clickonthenewscripttoopenit.
SetitsselectortotheIDthatyouspecifiedinStep2,precededbya#,forexample:#toc-content.
Pastethefollowingcodeinthescripteditor:
// Build the TOC
var toc = '';
merge.context.query("h1, h2").each(function() {
var pageNo = this.info().pageNo;
var text = this.text();
var level = this.tagName();
toc += '<p class="toc-entry ' + level + '">';
toc += '<span class="text">' + text + '</span>';
toc += '<span class="dots"></span>';
toc += '<span class="number">' + pageNo + '</span></p>';
});
results.html( toc );
// Repaginate the result
merge.section.paginate();
// Update the page numbers
var $numbers = query('.number');
merge.context.query("h1, h2").each(function( index ) {
var pageNo = this.info().pageNo;
var entry = $numbers.get( index );
if( entry ) {
entry.text( pageNo );
}
});
What the script does
Firstthescriptcreatesavariabletoholdthetableofcontents:toc.
Thenitcollectsall<h1>and<h2>elements-inotherwords,level1and2headings.Themerge.-
context.query(selector)functionsearchesacross all Print sections(see"query(selector)"on
page843).
Thequeryreturnsaresultset.Eachoftheelementsintheresultsetgoesthroughthecallbackfunction
definedineach()(see"each()"onpage717).
Thecallbackfunctiongetstheelement'spagenumber,textandHTMLtagname:
var pageNo = this.info().pageNo;
var text = this.text();
var level = this.tagName();
Page 412