Markdown Editor

by Sam Fereday

HTML

<div class="row">
  <button id="bold">Bold</button>
  <button id="emphasis">Emphasis</button>
  <button id="header-one">H1</button>
  <button id="header-two">H2</button>
</div>

<div class="row">
  <div id="text-body" contenteditable="true">Header One See the Markdown page for instructions on enabling Markdown for posts, pages and comments on your blog, and for more detailed information about using Markdown.</div>
</div>

CSS

body {
  font: 75%/1.4em arial;
}

div {
  box-sizing: border-box;
}

.row {
  width: 100%;
  padding-bottom: 1em;
}

.highlight {
  background: #333;
  color: #fff;
  resize: none;
}

#output {
  padding: 1em;
  clear: both;
}

#text-body {
  clear: both;
  width: 100%;
  min-height: 200px;
  border: 0;
  padding: 1em;
  resize: none;
  font-family: arial;
  background: #FFF;
}

JavaScript

// https://en.support.wordpress.com/markdown-quick-reference/
var textbox = document.getElementById("text-body"),
boldButton = document.getElementById("bold"),
emphButton = document.getElementById("emphasis"),
headerOne = document.getElementById("header-one"),
headerTwo = document.getElementById("header-two"),
lastHighlighted = null,
baseOffset = -1;

// Markdown types
var types = {
	bold: "**",
  emphasis: "*",
  headerOne: "#",
  headerTwo: "##"
}

// String modifier
function highlight(index, str, mod)
{

	if(str.length === 0)
		return;

	// Again, pretty broken...
  // var innerText = textbox.innerText,
  var innerText = textbox.innerHTML,
  newText = "";
  // index = innerText.indexOf(str);
  
  if(index >= 0)
  {
  
  	// Problem here assumes that if it finds the first instance of highlighted word, that's the one selected. This is not always the case at all. So we'll need to match the position of the string index too.
    // Start of string to index, then fill, then end of that string to end of whole string. So index needs to now be defined by something else, like the selection.
    if(!mod) {
  		newText = innerText.substring(0, index) + "<span class='highlight'>" + innerText.substring(index, index + str.length) + "</span>" + innerText.substring(index + str.length);
    } else {
    	newText = innerText.substring(0, index) + mod + innerText.substring(index, index + str.length) + mod + innerText.substring(index + str.length);
    }
    
    textbox.innerHTML = newText;
    
  }
  
  lastHighlighted = "";
  
}

// String range selector
function getSelectionText() {
    
    var text = "", result;
    
    // Selection range may well be broken...
    if (window.getSelection) {
        result = window.getSelection();
        text = result.toString();
        console.log(result);
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
        // to fix for IE
    }
    
   ...