Using Showdown with and without jQuery
Showdown (also known as PageDown) is a JavaScript parser for Markdown-formatted text. It’s used on this site to generate a formatted preview of your comment as you type it.
Implementing Showdown with plain JavaScript
Showdown is library-agnostic, meaning it doesn’t depend on any of the available JavaScript frameworks. Unless you’re already including a framework in your project, there’s no need to do so just to implement Showdown — you can just use plain JavaScript:
(function() {
// When using more than one `textarea` on your page, change the following line to match the one you’re after
var textarea = document.getElementsByTagName('textarea')[0],
preview = document.createElement('div'),
converter = new Markdown.Converter().makeHtml;
// Continue only if the `textarea` is found
if (textarea) {
preview.id = 'preview';
// Insert the preview `div` after the `textarea`
textarea.parentNode.insertBefore(preview, textarea.nextSibling);
// instead of `onkeyup`, consider using `oninput` where available: http://mathiasbynens.be/notes/oninput
textarea.onkeyup = function() {
preview.innerHTML = converter(eTextarea.value);
};
// Trigger the `onkeyup` event
textarea.onkeyup.call(eTextarea);
}
}());
Note: Instead of the keyup event, it would be better to use the input event where available, falling back to keyup.
Using Showdown with jQuery
If you’re using jQuery anyway, this can be rewritten as follows:
$(function() {
// When using more than one `textarea` on your page, change the following line to match the one you’re after
var $textarea = $('textarea'),
$preview = $('<div id="preview" />').insertAfter($textarea),
converter = new Markdown.Converter().makeHtml;
// instead of `keyup`, consider using `input` using this plugin: http://mathiasbynens.be/notes/oninput#comment-1
$textarea.keyup(function() {
$preview.html(converter($textarea.val()));
}).trigger('keyup');
});
Demo
I’ve uploaded a demo of the plain JavaScript-version. It works in every A-grade browser, including IE6. The jQuery version has identical functionality and browser support.
Comments
Luke wrote on :
Thanks for this dude, it’s perfect, just what I was looking for.
Miller Medeiros wrote on :
I added GitHub-style codeblock support + syntax highlight and posted it on jsbin motivated by @addy_osmany’s tweet. Cheers.
Update: And here’s an alternate version using a regular expression instead: http://jsbin.com/axaqob/edit#javascript,html