Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Markdown in text that's coming from a live preview in Javascript

I'm working on a website with ruby on rails where people can make posts and what not. The posts use Markdown for rendering the text just like Stack Overflow. Whenever a user is making a post, there is a live preview div right beneath the text area that show's the user what their post will look like, just like here on stack overflow. My problem is I don't know how to get the Markdown to render on the live preview.

My javascript code for the live preview is

window.onload = function(){
var idea = document.getElementById("idea-text");
try{
    idea.onkeyup = idea.onkeypress = function(){
        document.getElementById('live-preview').innerHTML = this.value.replace(/\n/g, '<br/>');
    }
}
catch(e){
}
}  

The text will always be plain text, any pointers on making the Markdown render?

Edit:

My solution to my dilemma was to use markdown-js from https://github.com/evilstreak/markdown-js Figuring out how to use this with node was painful however because I ran into multiple problems. I found a solution on https://rails-assets.org/#/components/markdown which provided a simple three step solution to my problem! My code to show a live-preview of text that renders mark down is

window.onload = function(){
var idea = document.getElementById("idea-text");
try{
    idea.onkeyup = idea.onkeypress = function(){
        document.getElementById('live-preview').innerHTML = markdown.toHTML(this.value);
    }
}
catch(e){
}
}
like image 512
Enigma Avatar asked Feb 23 '26 10:02

Enigma


1 Answers

You can use a library like markdown-js that expose a simple method to convert a markdown conte in html, then directly inject your html in your preview div.

like image 86
Davide Melfi Avatar answered Feb 25 '26 22:02

Davide Melfi