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){
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With