Thursday, October 2, 2014

Javascript TOC Robot

The list of books on Required Reading is starting to get a bit long, so I decided to add a table of contents (TOC). It's a drag to update the TOC everytime I add a book, so of course Javascript (JS) came to mind. But I didn't know whether Blogger uses jQuery so I decided to go old school and do puro JS.

First I added an id attribute to the book headers that I could use to link to them. At first I also thought that I could just grab all of the headers of type h2 but it turns out, duh, that there were a lot of h2 headers already in the template for the page, so I got a bunch of unrelated TOC entries. So instead I created a class that I could use to identify my book headers. Probably other ways I could have resolved that conundrum, so if you, yes you, have any bright ideas, please enlighten us! Thanks!

One cool thing I learned from pure JS is that document has an attribute similar to jQuery's $(Document).ready() function called document.body.onload, altho now I see in jQuery's documentation that the difference is that jQuery runs your JS as soon as the DOM is loaded and doesn't wait for assets like images to load as well, since they take longer.

Source

Here is the Gist of it.
Fork me on GitHub