wysywig

by Danilo Metzker

HTML

<div class="editor">
  <div class="menu">
    <a href="#" data-tag="b">B</a>
    <a href="#" data-tag="i">I</a>
  </div>
  
  <div class="content" contenteditable></div>
</div>

CSS

body{
  font-family: sans-serif;
}
.editor{
  border: 1px solid #000;
}

.editor .menu{
  display: flex;
  border-bottom: 1px solid #000;
}

.editor .menu a{
  padding: 8px;
  text-decoration: none;
  color: #000;
}
.editor .menu a.active{
  background-color: #000;
  color: #fff;
}

.editor .content{
  height: 200px;
  padding: 16px;
  outline: none;
}

JavaScript

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

function getSelectionElement(){
	if (window.getSelection) {
    element = window.getSelection();
  } else if (document.selection && document.selection.type != "Control") {
    element = document.selection;
  }
    return element.anchorNode;
}

function createNode(tag, text) {
		var element = document.createElement(tag)
    element.innerHTML = text;
    return element;
}

function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(replacementText);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.innerHTML = replacementText;
    }
}

$(".editor .menu a").click(function(e){
	e.preventDefault();
  
  let tag = $(this).data("tag");
  
  let text = getSelectionText();
  
  // already formated, then remove format
  if(currentTagName == tag){
  	text = currentElement.textContent;
  	textElement = document.createTextNode(text);
    
    // replace <b>sample</b> with sample
    currentElement.parentNode.replaceChild(textElement, currentElement);
  }else{
  
  	//replace selected node with <b>sample</b> node
  	replaceSelectedText(createNode(tag, text));
  }
  
});

var currentElement = false;
var currentTagName = false;

$(".editor .content").click(function(e){
	currentElement = getSelectionElement().parentElement;
	currentTagName = currentElement.tagName.toLowerCase();
  
  $(".editor .menu a").each(function(i, el){
  	$(el).removeClass("active");
    if($(el).data("tag") ==...