Using code tags and jQuery to dynamically load CodeMirror Instances

By Hawkee on Feb 12, 2013

This uses jQuery to convert an HTML string containing < code > tags into language specific CodeMirror containers. This supports a "lang" attribute to indicate the CodeMirror mode for each code block. Here is some example input:

Here is some PHP code:
<code lang=php>
    print "Hello World!";

And here is some Python code:
<code lang=python>
    print "Hello World!";

Next you'll need to have this template somewhere on your DOM to use for each replacement block. You can add headings or styles to this to customize your code blocks.

<div id='code_template' style="display: none;">     

Now here is the JavaScript that will find each < code > block, replace it with our template above, attach a CodeMirror instance, load the CodeMirror mode JavaScript file and set the mode for the syntax highlighter. If the language mode does not exist or no lang tag is found it will default to 'clike'.

function setMode(cm, mode) {
    if(mode !== undefined) {
        var script = '/codemirror/mode/'+mode+'/'+mode+'.js';

        $.getScript(script, function(data, success) {
            if(success) cm.setOption('mode', mode);
            else cm.setOption('mode', 'clike');
    else cm.setOption('mode', 'clike');

$(document).ready(function () {
    $('code').each(function() { 

        var lang = $(this).attr('lang');
        var template = $('#code_template').clone();

        // Take the code and put it into the textarea.

        var cm = CodeMirror.fromTextArea($(this).find('textarea')[0], {
                lineNumbers: true,
                matchBrackets: true

        setMode(cm, lang);


Sign in to comment.
Sorasyn   -  Feb 12, 2013

Nice, and clean interface. I was looking into some JQuery, playing around with some web development. Still am actually, time permitting. It's a nice "short-hand" to Javascript if you will.

Hawkee  -  Feb 12, 2013

jQuery is very handy for manipulating a page on the fly. You can reference page elements just as you would with CSS.

Sign in to comment

Hawkee   -  Feb 12, 2013

This is what we use here on the snippet pages.

ProIcons  -  Feb 14, 2013 i thought GeSHI was better but annyway

Hawkee  -  Feb 14, 2013

GeSHI is only a syntax highlighter. CodeMirror is a code editor and a syntax highlighter. Ace is another editor/highlighter which is quite comparable to CodeMirror. GeSHI is starting to lose support and has started to fall into obscurity with its lack of a real time editor.

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.