Forum How do I...?

JavaScript TOC: how to avoid zero page numbers…

Infarinato
…for TOC entries pointing at hidden elements.

(I guess this might have to wait until the DOM style property is implemented in v8.1, but I’ll ask anyway. :mrgreen:)

If you automatically generate a table of contents out of all the headers in your document (h1,…,h6) via JavaScript and, say, one of them is “hidden”, when you output the page counter with your CSS, you get a 0 (zero) as the corresponding page number (and a broken link in the PDF document).

Is there a way to avoid these headers from showing in the TOC (apart, of course, from knowing which ones they are at the outset, and explicitly exclude them one by one with JavaScript)?

Many thanks.
mikeday
What is your criteria for an element being hidden? At the moment there is no way to tell if an element has a "display: none" CSS rule applied to it, unless it was specified in the style attribute of the element in question.
Infarinato
mikeday wrote:
At the moment there is no way to tell if an element has a "display: none" CSS rule applied to it, unless it was specified in the style attribute of the element in question.

Precisely my point. :(

There is no “overall criterion” for an element to be hidden: usually, it will be part of an [ancestor] element we have explicitly hidden from the print version of the page with a “display: none” in the [print/Prince] CSS.

As you might remember, we are using JavaScript to automatically generate a table of contents of a PDF booklet consisting of a collection of [user-selected] web pages on our site… with all the issues that entails! :D Of course, we can intercept most of the hidden headers and add an explicit “noPrince” class on each of them, which we can then use (and have used) to explicitly exclude them from the TOC, but, given the scope of our target set, there is always a chance of missing a few of them… :?
mikeday
If you are selecting ancestor elements by ID, perhaps you could use those IDs to find them with JavaScript. Or better yet, use JavaScript to hide the elements by removing them from the document altogether. That way the hiding and the table of contents generation is guaranteed to always be synchronised.
Infarinato
mikeday wrote:
…use JavaScript to hide the elements by removing them from the document altogether.

Thank you, Mike: that’s a good idea! :D

It means that we’ll have to maintain the same list of hidden elements (usually referenced by class, not id) in two places (CSS and JavaScript), but we can probably live with that… :)