block by nitaku 10640487

Showdown

Full Screen

A simple test for the showdown.js library. A web page author can define the content by writing it in markdown, then have it automagically converted into HTML.

The implementation makes use of <script> tags in a not-so-standard fashion, specifying text/x-markdown as the script type. By using standard query selectors, the code finds all the script tags containing markdown, then invokes showdown.js to convert the content into HTML. The <script> tag is then replaced by a <div> tag, containing all the generated HTML.

Older browser can have a hard time executing this code, because of query selectors (see caniuse.com). Another way of implementing it can make use of jQuery, d3.js or other, higher-level DOM manipulation libraries.

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Showdown example</title>
        <script src="showdown.js"></script>
        <style>
            body {
                font-family: sans-serif;
            }
        </style>
    </head>
    <body>
        <script type="text/x-markdown">
This is a *test*.
         </script>
        <p>This is HTML content.</p>
        <script type="text/x-markdown">
This is another **test**.

# This is a title

## This is another title
This is text.

This is a new paragraph.

> This is a blockquote...
blockquote continues

- This
- is
- an
- unordered
- list

This is some text to work around a `showdown.js` issue (ordered lists are mixed up with unordered lists).

1. This
2. is
3. an
4. ordered
5. list

[This is a link](//www.google.com) to Google.
        </script>
    </body>
    <script>
        // find all text/x-markdown scripts and replace them with a div containing the converted markdown
        var converter = new Showdown.converter();
        var markdown_els = document.querySelectorAll('script[type="text/x-markdown"]');
        for (var i=0; i < markdown_els.length; i++) {
            var text = '';
            for (var j=0; j < markdown_els[i].childNodes.length; j++) {
                var child = markdown_els[i].childNodes[j];
                if (child.nodeName === '#text') {
                    text = child.nodeValue;
                    break;
                }
            }
            var new_el = document.createElement('div');
            new_el.innerHTML = converter.makeHtml(text);
            markdown_els[i].parentNode.replaceChild(new_el, markdown_els[i]);
        }
    </script>
</html>