Heading Anchors via jQuery

| No Comments

Markdown is my text markup of choice… but one thing it doesn’t have is the ability to add classes or id elements to any of the html. Because what I wanted to do wasn’t critical without JavaScript enabled, I used jQuery to implement the same solution that the HeadingAnchors plugin does… but in JavaScript. This also creates a navigation menu using all the H2 tag heading text.

Code

Requires dirify function and dirify_table.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("jquery", "1.3.2");

    // When the document is ready for javascript fun...
    google.setOnLoadCallback(function() {
        // initalize variable
        var $menu = '';
        // select all the page headings, assuming that h1 is only used once (for the main page title)
        $("h2, h3, h4, h5, h6").each(function () {
            // Dirity heading text to create the anchor
            $anchor = dirify($(this).text());
            // If heading is h2, add list item to menu
            if ("H2" == $(this)[0].nodeName) {
                $menu += '<li><a href="#' + $anchor + '">' + $(this).text() + '</a></li>';
            };
            // Append anchor to heading
            $(this).append('<a title="Link to this section" class="anchor" href="#' + $anchor + '"> ΒΆ</a>').attr('id', $anchor);
        });
        // Add menu to sidebar
        $('.sidebar').prepend('<div class="tag-menu"><h3>Tag Types</h3><ul>' + $menu + '</ul></div>');
    });
</script>

Leave a comment