Generate Table of Contents from Heading Tags in JavaScript

I recently needed a way to generate a Table of Contents in some documentation. I wanted it to be automatic so I could freely write without having to worry about updating the table of contents. This turned out to be more difficult than I intended with very little available through Google. So I wrote my own function and making it available here for free!


Set the innerHTML of a DOM node to the string returned from generateTOC where you want the Table of Contents to appear. Pass the parent DOM node into the function and optionally a start tag number if you want to start the table of contents at <h2> instead of “

//save references to our DOM nodes
var navNode = document.getElementById("nav");
var parentNode = document.getElementById("content");

//generate the TOC and set the nav innerHTML to it
var generatedHTML = generateTOC(parentNode);
navNode.innerHTML = generatedHTML;

Feel free to direct all questions to the gist.

Advergaming - The feedback loop between advertisers and players

Feedback loop

Advergaming: The feedback loop of players leading to advertisers which benefit and lead to more players. Rinse repeat.

As an incentive to play a game, you have the potential of earning benefits. I don’t mean simply gambling; I’m talking about participation in a game leading to real-world rewards from either other players or advertisers with a vested interest.

The more players a game has, the more valuable it would be for advertisers. The more advertisers are involved in the game, the more incentives there are to play the game thus spawning more players… and so on.

There are three ways to integrate this into a game that I can think of:

  1. Sponsorship - a player is ‘sponsored’ by an advertiser to display an ad in-game or through an avatar.

  2. Acquisition - in-game properties or items owned by a player can be bought by an advertiser to display ads or an external link.

  3. Campaign - advertisers can offer prizes to winners in a game run by the advertiser complete with their branding.

Pixenomics is game modelled after Acquisition. Players own pixels on a large canvas which can be bought by advertisers seeking that space on the board for ads.

To kickstart the loop you need an amount of players that is large enough to get the interest of advertisers. To get players, especially organically, the game must be fun with or without other players (something Pixenomics is lacking).

As this is just a concept I have no real studies or real-world examples to show but I would be interested in seeing how an idea like this could be executed.

Custom Canvas Drawing in CraftyJS

A lot of people have asked about this and I thought it’s about time I write up a quick example for custom drawing on the canvas in a way that doesn’t break the redraw regions.

The first thing to ensure is that the entity’s width and height is large enough to encapsulate the entire drawing so the redraw region manager knows how much to clear.

The second thing to do is overwrite the draw method. In there we can do our custom 2D canvas drawing.

My example is a Circle drawer. It requires a radius and color:

As you can see I set the width and height to the size of the circle (radius * 2).

I also create a draw method which draws a circle at the entity’s x and y position with an offset of the the radius.

It’s as simple as that. We can have some fun with the custom renderer by adding the Tween component and decreasing the radius over 500 frames.

External Documentation Proposal for Exposed APIs

I have been playing around with various methods of documentation and for a while I thought the way to go was inline documentation where the documentation exists within the source code, but I’ve noticed a few flaws in this approach.

Who is the target reader?

Inline documentation doesn’t make sense if the end user has no knowledge or interest in the source. It should exist to teach the reader how and why the code works from the perspective of someone interested in the internals. For a developer who just wants to make use of the API, why include it with the source?

Forcing Object-Oriented-ness

JSDoc in particular generates documentation similar to JavaDoc; a strictly Object Oriented language. This doesn’t cross over well when you have things such as chaining, currying or other JavaScript oddities.

The solution

Damon Oehlman wrote about using a Domain Specific Language (DSL) in an external document for API documentation. In his example developers would use some specific representations of how to use the API using text.

I imagine a structure where the documentation mimics the source code file structure, but for every code file a documentation file exists in its place. These files will be a superset of Markdown with extra formatting to denote namespaces, signature overloading, types and internal links. A generator would then convert the structure into HTML pages.

I’ll start with an example:

>Crafty(selectors:string) => <Core.Entity>
>Crafty(entityID:number)  => <Entity>
Select a set of or single entities by components or an entity's ID.

Crafty uses syntax similar to jQuery by having a selector engine to 
select entities by their components. Selecting by multiple components
is done by seperating with a comma or a space. A comma is similar
to OR where the entities can match one or more of the components. 
A space is similar to AND where entities have to match all the 

    Crafty("Hello 2D Component")
    Crafty("Hello, 2D, Component")

The first selector will return all entities that has the component 
MyComponent. The second will return all entities that has Hello 
and 2D and Component whereas the last will return all entities that
has at least one of those components (or).

**See also: <>**

In Markdown, a line starting with a single # means Heading 1. This will also denote a unit of code to document; such as a function, namespace or variable. It will also be used as the path for any other references in the documentation.

Grouping can be done by creating a path with a dot . as the separator. This could be used for categorising units of code or specifying a namespace path or even both at the same time!

As per Damon’s example, the greater than symbol > denotes a method signature where you specify the arguments as name:type (name is optional). The return type is specified after =>.

In my example the return type is wrapped in <angled brackets>. This represents an internal link to another unit. You may either specify the full path (as specified after the #) or use a subset of the path (assuming no collision) and the generator will pick it up.

Special files could be used for an Introduction, License information and even tutorials.

#Tutorial.RPG Demo
My tutorial formatted in Markdown!

The output of this format would be a hierarchy of units where each unit has its own HTML page. Templates for headers and footers would allow stronger customisation.

I would be interested in hearing some ideas on the subject. I think external documentation can create a greater separation between how to use the code and how the code works. It avoids huge source code files and can let the developers document in the format that suits the project. Sneak Peek

I had a go playing around with Drupal for the new and improved #BBG community site. It was surprisingly easy to get started and build a dynamic site. The content type feature was very helpful for customizing the data that BBG members will be posting.

The current content types are:

  • Projects: This is if members have created a project and want to share it. You can specify the repo and homepage.

  • Links: Sharing relevant links for HTML5 game development.

  • Text Posts: Purely text for those who don’t want a full blog but feel like writing about what they are working on.

  • Screenshots: An image and short description of the latest preview for any work in progress projects.

  • Poll: A standard poll to get a general opinion from the community.

All these posts will be aggregated under the members page as well as categorised for newcomers. This entire site was very quick to put together thanks to some great Drupal modules, not to mention a handy skill to learn for any future dynamic sites.

I have included a screenshot and will upload the site in the next couple of days or so.

A new direction for #BBG

If you haven’t heard of #BBG, check it out now! It’s an IRC channel on dedicated to browser based games (regardless of your chosen tech) and boasts a variety of industry professionals from authors to engine developers.

We have a site dedicated to the community at but we think it’s time for a revamp.


First of all we want to add categories on the home page so newcomers can see the latest and greatest games, tutorials, podcasts, blogs etc from the community and find out the developers responsible. The best part is they can then chat to the developers on #BBG!

Profile Page

Members should be able to post links to anything new they are working on or have recently created. This would be posted on their profile page as well as in a feed on the home page (and a tweet from @HashBBG).


We will need to add sections for the various events such as the BBGMeetup and BBGChallenge. The BBGMeetup will be more frequent once we secure some members who want to participate regularly.

Ask an HTML5 Dev

Myself and Andrew J Baker started a series on HTML5Grind where the community would decide on a question to ask professional HTML5 developers and we would compile a list of responses from members. We intend to bring that back.

Essentially we want a place where BBG members can post the amazing stuff they’re working on and where newcomers can discover the great developers behind the work. The site will be a community effort so any help is appreciated.

Recent Posts widget in Tumblr

Pure JavaScript and less than 600 bytes. This will create an unordered list of recent posts from the blog of your choosing in a div that will replace the script tag.

Unminified (864 bytes):

<script type="text/javascript">
(function(blog, limit) {
limit = +limit || 10;

var scriptTags = document.getElementsByTagName('script');
var scriptNode = scriptTags[scriptTags.length - 1];
var recent = document.createElement("div");
recent.setAttribute("class", "widget");
recent.setAttribute("id", "TumblrRecentPosts");

var script = document.createElement("script");
script.src = "http://" + blog + "/api/read/json";
script.onload = function(data) {
    if(!tumblr_api_read) return;

    var response = tumblr_api_read.posts;
    var post;
    var len = Math.min(response.length, limit);
    var html = "<ul>";

    for(var i = 0; i < len; ++i) {
        post = response[i];
        html += "<li><a href='" + (post['url-with-slug'] || post.url) + "'>" + 
            post['regular-title'] + "</a></li>";

    recent.innerHTML = html;


})("", 30); //enter your settings here

Minified (573 bytes):

<script type="text/javascript">
(function(d,e){var  e=+e||10,
for(var a=tumblr_api_read.posts,c,d=Math.min(a.length,e),f="<ul>",g=0;
g<d;++g)c=a[g],f+="<li><a href='"+(c["url-with-slug"]||c.url)+"'>"+
c["regular-title"]+"</a></li>";b.innerHTML= f}};
("",30); //enter your settings here


Place the script tag where you want the unordered list to be in your HTML document. Enter the blog URL in the arguments and specify a limit to the number of posts to list (default being 10). My blog is or and I specified a limit of 30 posts.

How it works:

It uses the old Tumblr API (accessed via http://{Tumblr URL}/api/read/json) and runs it as a script. The script sets a global variable called tumblr_api_read. This is a large object which includes public blog information and posts.

Replacing the script tag is done by grabbing all script tags through document.getElementsByTagName("script") where the last script will be the one currently executing (the one we want to replace). We can then append our created div to the parent of the script tag.

Self promotion should be encouraged

The web seems to favour curation over creation. Self promotion is generally frowned upon and most will tell you sharing a mix of other’s links and your own is more acceptable; but why? This only encourages curation and stunts creation.

Content is king

Once upon a time this was the mantra of the web. Content above all else is most important. By this logic it doesn’t matter where the content came from, as long as it is good quality content.

Self promotion is not always spam

Some regard self promotion as a form of spam. Spam implies the content is unwanted which to me depends on the quality and frequency as opposed to whether the owner submited it for self gain.

Curation promotes reposts and stale content

We should be actively seeking new and quality content rather than sharing an already popular link otherwise known as reposts.

Good content goes to waste

It is very hard for content creators to get noticed. Think of how many blogs, tech articles, tutorials, videos, stories, games, music, tools, software, services or webcomics exist on the web. Some of them might be good, some might be great and not all of them will be discovered by curators.

Different monetization methods for HTML5 games and apps

Monetization is one of many challenges when creating a game or app in HTML5. After all the effort it would only be fair to recieve minor compensation to keep development alive. The problem is deciding how to earn money from your creation while not affecting it’s growth.

A standard method is to offer a freemium model (free with ads, pay for more content). Another is in-game purchases. I was thinking about various other ways it could be done where the player has more incentive to pay.


Players would have to buy the game to enter (say for $1). The prize could be 10% of the proceeds or any other reward. Players can win by beating a level first or holding the highest score by a certain date.

It would encourage players to buy the game, play it and most of all share it with friends as it would increase the winnings.

In-game product placement

This is just another form of advertising but more subtle than an attention grabbing advertisment blocking half the screen. In-game items that advertise a brand name would be less obtrusive and most likely more effective. Finding sponsors wouldn’t be easy but there are other sources such as affiliate marketing (see Amazon Affiliate Program).

Sell unobfuscated and commented source code

With HTML5 games and apps the source code will always be there for all to see even if obfuscated. One may as well either publicly release it or offer the full commented and styled source code for a fee, should developers want to learn or expand on it.


Companies like CafePress offer the ability to customise T shirts, stickers, posters and various types of merchandise to sell to loyal fans or even as a prize for the aforementioned raffle.

There is definitely room for some creative forms of monetization that benefit the developer as well as the player. I would be interested in hearing other ideas.

Simulating a player

Automated tests are a great way to do a sanity check against any changes you feel might affect other areas. You can quickly run some tests and ensure components do as they’re expected. This doesn’t cross over well into game development because other factors come into play such as input, randomization, networking and other variables that affect the program.

What’s really needed is to be able to simulate a player and observing the outcome exactly as it was when it was logged. To do this, every single variable that affects the game state has to be logged with a timestamp so it can be played back at the exact same interval. This includes randomly generated numbers, click or keyboard events, network data, time etc etc.


There are more use cases than just automated tests. You can use it for benchmarking so that every platform you test will involve the same gameplay and actions. Domsz has done this for his game engine, ImpactJS.

Validate High Scores

Blindly accepting any high score as valid can and probably will lead to people sending requests with an obviously fake score. Sending the data to the server and replaying it to see what the end result is can be used to determine whether they cheated or not.


Simulating the input on the server can be used for multiplayer games to keep two or more players in sync and prevent players from cheating. There’s obviously more to it than that but it’s an idea.


It’s now a common gameplay component to allow players to replay part of the game or for a stylised effect such as killcam.

For games that are heavily randomly generated (which a lot are), there is the option to save the seed used so all that is needed is to use the same seed when replaying to generate the same random numbers. Not all random functions provide this feature (JavaScript doesn’t). Another way around this is to log the generated value so when you replay it, use the same number that was generated last time.

There is a great post about implementing such as thing known as Deterministic Games. Unfortunately it is mainly relevant to the LWJGL framework.