I'm having a problem with Codemirror where the live preview mode is not working for Markdown. I'm basically just trying to achieve the same effect as on SO. As it stands the live preview works for HTML but not Markdown. I've followed several of the demos and tried a few things with no luck and I'm here as a last resort. Here is the relevant code:
In the head of my document I'm loading:
<script src="editor/lib/codemirror.js"></script>
<link rel="stylesheet" href="editor/lib/codemirror.css">
<script src="editor/lib/util/overlay.js"></script>
<script src="editor/mode/markdown/markdown.js"></script>
Note: I have the Codemirror files inside a folder called editor
. That's the only real deviation from the normal setup I've done.
Then in the <body>
of my document I've got a <form
> with 2 elements:
<textarea id="content" name="content"></textarea>
and
<iframe id="preview"></iframe>
Then at the bottom of my page I'm running the following JavaScript (I'm using jQuery 1.8.2 too by the way):
// Initialize the editor when document finishes loading
jQuery(document).ready(function() {
var delay;
var editor = CodeMirror.fromTextArea(document.getElementById("content"), {
lineNumbers: false,
mode: 'markdown',
matchBrackets: false,
theme: "ambiance",
onChange: function() {
clearTimeout(delay);
delay = setTimeout(updatePreview, 300);
}
});
// Initialize the live-preview mode
function updatePreview() {
var previewFrame = document.getElementById('preview');
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
setTimeout(updatePreview, 300);
});
I can't figure out what I'm doing wrong. I've tried loading overlay mode along with XML to no avail. I found 2 posts here but they weren't exactly relevant and the code didn't work for me. The live preview is showing up and updating but the problem is that I'm getting just a single string of text with no formatting.
So, for example, the following Markdown: # Heading 1
A paragraph with __bold__ *text*.
And [a link](http://example.com)
Will output this in the live preview iframe exactly as I type it here:
# Heading 1 A paragraph with __bold__ *text*.And [a link](http://example.com)
It doesn't make the underscores or asterisks into bold or italicized text and completely ignores line breaks.
Any ideas as to what's going wrong? I couldn't even modify the demos to get it to work. I must be missing some knowledge.
Browsers don't display markdown, they display HTML. You'll have to add a step where you convert them markdown to HTML using, for example, https://github.com/chjj/marked.