DEV Community

Cover image for Build your own WYSIWYG editor (HTML, CSS & pure JavaScript)
webdeasy.de
webdeasy.de

Posted on • Originally published at webdeasy.de

Build your own WYSIWYG editor (HTML, CSS & pure JavaScript)

Are you annoyed by missing or unnecessary functions in WYSIWYG editors? No problem! Here I show you how to create your own fully functional WYSIWYG editor with HTML, CSS and JavaScript.

WYSIWYG stands for β€œWhat You See Is What You Get”. This refers to text editors that directly display a text with all formatting and we can change the formatting as we wish. They are also often called Rich Text Editors.

Table of contents

Many of the available editors, like TinyMCE, work really well and are great for most projects. However, you might find one or the other editor a bit overloaded, too complicated or you just want to program your own WYSIWYG editor.

The following demo is created with pure HTML, CSS and pure JavaScript. In the next steps I will go into the implementation of this WYSIWYG editor in detail and at the end you will be able to program your own editor

Here is the running demo version of the editor we are about to code together.

Also on my blog webdeasy.de I use this rich text editor for the comments! πŸ™‚

1. Design the HTML framework

Our main HTML task is to create the editor toolbar. For this we have an outer container .wp-webdeasy-comment-editor. This includes a container for the toolbar .toolbar and a container for the different views (Visual view & HTML view) .content-area.

<div class="wp-webdeasy-comment-editor">
  <div class="toolbar">
  </div>
  <div class="content-area">
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

1.1 The Toolbar

I have arranged the toolbar in two lines (.line), but there can be as many as you like. There are also several .box boxes in each line for a rough outline of the formatting options.

In such a box there is always a span element with a data action (data-action). This data action contains the command that is to be executed later on the selected text. In addition, some elements have a data tag name (data-tag-name). This is important later so that we can set the button active if the current text selection has a certain formatting.

This is what the two toolbar lines look like in HTML:

<div class="line">
  <div class="box">
    <span class="editor-btn icon smaller" data-action="bold" data-tag-name="b" title="Bold">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/bold.png"/>
    </span>
    <span class="editor-btn icon smaller" data-action="italic" data-tag-name="i" title="Italic">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/italic.png"/>
    </span>
    <span class="editor-btn icon smaller" data-action="underline" data-tag-name="u" title="Underline">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/underline.png"/>
    </span>
    <span class="editor-btn icon smaller" data-action="strikeThrough" data-tag-name="strike" title="Strike through">
      <img src="https://img.icons8.com/fluency-systems-filled/30/000000/strikethrough.png"/>
    </span>
  </div>
  <div class="box">
    <span class="editor-btn icon has-submenu">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-left.png"/>
      <div class="submenu">
        <span class="editor-btn icon" data-action="justifyLeft" data-style="textAlign:left" title="Justify left">
          <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-left.png"/>
        </span>
        <span class="editor-btn icon" data-action="justifyCenter" data-style="textAlign:center" title="Justify center">
          <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-center.png"/>
        </span>
        <span class="editor-btn icon" data-action="justifyRight" data-style="textAlign:right" title="Justify right">
          <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-right.png"/>
        </span>
        <span class="editor-btn icon" data-action="formatBlock" data-style="textAlign:justify" title="Justify block">
          <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-justify.png"/>
        </span>
      </div>
    </span>
    <span class="editor-btn icon" data-action="insertOrderedList" data-tag-name="ol" title="Insert ordered list">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/numbered-list.png"/>
    </span>
    <span class="editor-btn icon" data-action="insertUnorderedList" data-tag-name="ul" title="Insert unordered list">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/bulleted-list.png"/>
    </span>
    <span class="editor-btn icon" data-action="outdent" title="Outdent" data-required-tag="li">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/outdent.png"/>
    </span>
    <span class="editor-btn icon" data-action="indent" title="Indent">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/indent.png"/>
    </span>
  </div>
  <div class="box">
    <span class="editor-btn icon" data-action="insertHorizontalRule" title="Insert horizontal rule">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/horizontal-line.png"/>
    </span>
  </div>
</div>
<div class="line">
  <div class="box">
    <span class="editor-btn icon smaller" data-action="undo" title="Undo">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/undo--v1.png"/>
    </span>
    <span class="editor-btn icon" data-action="removeFormat" title="Remove format">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/remove-format.png"/>
    </span>
  </div>
  <div class="box">
    <span class="editor-btn icon smaller" data-action="createLink" title="Insert Link">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/add-link.png"/>
    </span>
    <span class="editor-btn icon smaller" data-action="unlink" data-tag-name="a" title="Unlink">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/delete-link.png"/>
    </span>
  </div>
  <div class="box">
    <span class="editor-btn icon" data-action="toggle-view" title="Show HTML-Code">
      <img src="https://img.icons8.com/fluency-systems-filled/48/000000/source-code.png"/>
    </span>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

In my editor I use icons from Icons8. Therefore I have to insert a corresponding note on my page. If you use your own icons this is not necessary for you.

The Data Action is the command that will be executed later on the selected text. There is a list of MDN web docs for this purpose. So you can easily extend the editor with more commands here.

1.2 Visual and HTML view

In the content area we have two sections: An HTML view and a visual view. For this we create a container .visual-view, which also gets the property contenteditable. This property allows us to edit content directly inline without input. Feel free to try this out if you don’t know this feature.

<div class="visuell-view" contenteditable>
</div>
Enter fullscreen mode Exit fullscreen mode

We also add a textarea .html-view for the HTML view, because we want to switch between HTML and visual view later in the editor.

<textarea class="html-view"></textarea>
Enter fullscreen mode Exit fullscreen mode

1.3 Insert modal (pop-up) for links

This modal is opened when we want to insert a link. There you have the possibility to enter the link and choose if you want to open the link in a new window.

<div class="modal">
  <div class="modal-bg"></div>
  <div class="modal-wrapper">
    <div class="close">βœ–</div>
    <div class="modal-content" id="modalCreateLink">
      <h3>Insert Link</h3>
      <input type="text" id="linkValue" placeholder="Link (example: https://webdeasy.de/)">
      <div class="row">
        <input type="checkbox" id="new-tab">
        <label for="new-tab">Open in new Tab?</label>
      </div>
      <button class="done">Done</button>
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

1.4 Full HTML code

➑️ Check out the full code of the HTML file here

2. Style WYSIWYG editor

I have converted my SCSS code into normal CSS here so that everyone can understand it.

But I don’t explain anything else about this, because CSS basics should be clear, if you want to program such an editor. Of course you can also use your own styles here.
➑️ Check out the full code of the CSS file here

3. Programming functions in JavaScript

3.1 Declare variables

In JavaScript we now have to implement some functions. To do this, we first declare and initialize important elements of our editor:

const editor = document.getElementsByClassName('wp-webdeasy-comment-editor')[0];
const toolbar = editor.getElementsByClassName('toolbar')[0];
const buttons = toolbar.querySelectorAll('.editor-btn:not(.has-submenu)');
const contentArea = editor.getElementsByClassName('content-area')[0];
const visuellView = contentArea.getElementsByClassName('visuell-view')[0];
const htmlView = contentArea.getElementsByClassName('html-view')[0];
const modal = document.getElementsByClassName('modal')[0];
Enter fullscreen mode Exit fullscreen mode

3.2 Assign functions to toolbar buttons

To avoid programming each function individually we have already created a data action (data-action) in the HTML with the command. Now we simply register the click on these buttons in a loop:

for(let i = 0; i < buttons.length; i++) {
  let button = buttons[i];

  button.addEventListener('click', function(e) {
  });
}
Enter fullscreen mode Exit fullscreen mode

With the following line we read the action from the data action (in the HTML).

let action = this.dataset.action;
Enter fullscreen mode Exit fullscreen mode

We include a switch-case statement because inserting a link and switching the HTML view and the visual view requires even more from us.

switch(action) {
  case 'toggle-view':
    execCodeAction(this, editor);
    break;
  case 'createLink':
    execLinkAction();
    break;
  default:
    execDefaultAction(action);
}
Enter fullscreen mode Exit fullscreen mode

For β€œnormal” functions we use the execDefaultAction(action) function. There only the execCommand() function of JavaScript is executed with the data action of the respective button.

function execDefaultAction(action) {
  document.execCommand(action, false);
}
Enter fullscreen mode Exit fullscreen mode

JavaScript provides us with a great function document.execCommand(). This allows us to apply our action to the selected text. You can find the documentation for this function here.

Note: The execCommand() function is deprecated, but is currently still supported by all browsers. As soon as there should be problems here, I will update the original post on my blog!

The second parameter of execCommand() must be set to false. With this we disable a small UI that would be displayed in old Internet Explorer versions, for example. But we don’t need this and Firefox or Google Chrome don’t support these functions anyway.

When we want to switch between the HTML view and the visual view, we fade in the other one and swap the contents.

function execCodeAction(button, editor) {
  if(button.classList.contains('active')) { // show visuell view
    visuellView.innerHTML = htmlView.value;
    htmlView.style.display = 'none';
    visuellView.style.display = 'block';
    button.classList.remove('active');     
  } else {  // show html view
    htmlView.innerText = visuellView.innerHTML;
    visuellView.style.display = 'none';
    htmlView.style.display = 'block';
    button.classList.add('active'); 
  }
}
Enter fullscreen mode Exit fullscreen mode

3.3 Program link modal (pop-up) functionality

Next we want to be able to insert a link. For this purpose, I have already provided a modal in the HTML, i.e. a kind of pop-up.

In the following function this is shown and the current text selection of the editor is saved via saveSelection(). This is necessary because we focus another element in our popup and thus our text selection in the editor disappears. After that, the close and submit buttons are created.

function execLinkAction() {  
  modal.style.display = 'block';
  let selection = saveSelection();
  let submit = modal.querySelectorAll('button.done')[0];
  let close = modal.querySelectorAll('.close')[0];
}
Enter fullscreen mode Exit fullscreen mode
function saveSelection() {
    if(window.getSelection) {
        sel = window.getSelection();
        if(sel.getRangeAt && sel.rangeCount) {
            let ranges = [];
            for(var i = 0, len = sel.rangeCount; i < len; ++i) {
                ranges.push(sel.getRangeAt(i));
            }
            return ranges;
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Now we need a click event to insert the link. There we additionally save whether the link should be opened in a new window, load the selection from the text editor again with restoreSelection() and then create a new a element for it in line 13 and set the link from the link input.

In line 16 we then insert the created link around the text selection.

The modal is then closed, the link input is cleaned and all events are deregistered.

function execLinkAction() {  
  // ...  
  // done button active => add link
  submit.addEventListener('click', function() {
    let newTabCheckbox = modal.querySelectorAll('#new-tab')[0];
    let linkInput = modal.querySelectorAll('#linkValue')[0];
    let linkValue = linkInput.value;
    let newTab = newTabCheckbox.checked;    

    restoreSelection(selection);

    if(window.getSelection().toString()) {
      let a = document.createElement('a');
      a.href = linkValue;
      if(newTab) a.target = '_blank';
      window.getSelection().getRangeAt(0).surroundContents(a);
    }
    modal.style.display = 'none';
    linkInput.value = '';

    // deregister modal events
    submit.removeEventListener('click', arguments.callee);
    close.removeEventListener('click', arguments.callee);
  });  
  // ...
}
Enter fullscreen mode Exit fullscreen mode
function restoreSelection(savedSel) {
    if(savedSel) {
        if(window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            for(var i = 0, len = savedSel.length; i < len; ++i) {
                sel.addRange(savedSel[i]);
            }
        } else if(document.selection && savedSel.select) {
            savedSel.select();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

We also give the close button a function that simply hides the modal, clears the link input, and deregisters the two events.

function execLinkAction() {  
  // ...  
  close.addEventListener('click', function() {
    let linkInput = modal.querySelectorAll('#linkValue')[0];

    modal.style.display = 'none';
    linkInput.value = '';

    // deregister modal events
    submit.removeEventListener('click', arguments.callee);
    close.removeEventListener('click', arguments.callee);
  });
}
Enter fullscreen mode Exit fullscreen mode

3.4 Enable toolbar buttons when formatting is selected

If a text is selected in the WYSIWYG editor, we also want to highlight the corresponding formatting button. This way we always know what formatting a word or paragraph has.

To do this, we insert the registration of the selectionchange event at the very top, directly after the declaration of the variable.

// add active tag event
document.addEventListener('selectionchange', selectionChange);
Enter fullscreen mode Exit fullscreen mode

We then create the callback function, which first removes this class from all toolbar buttons with .active class. After that we check if our selection is even in our WYSIWYG editor (line 12). Then we call the parentTagActive() function and pass the first parent HTML tag of the current text selection.

function selectionChange(e) {

  for(let i = 0; i < buttons.length; i++) {
    let button = buttons[i];

    // don't remove active class on code toggle button
    if(button.dataset.action === 'toggle-view') continue;

    button.classList.remove('active');
  }

  if(!childOf(window.getSelection().anchorNode.parentNode, editor)) return false;

  parentTagActive(window.getSelection().anchorNode.parentNode);
}
Enter fullscreen mode Exit fullscreen mode

I defined the parentTagActive() function recursively, so that there can be multiple active tags. So if a word is italic, bold and underlined all three toolbar buttons are set active. For this reason, the individual buttons in the HTML have been given the data tag name (data-tag-name).

The text alignment is handled in the same way, so we can see whether the text is left-aligned, right-aligned, justified or centered.

function parentTagActive(elem) {
  if(!elem ||!elem.classList || elem.classList.contains('visuell-view')) return false;

  let toolbarButton;

  // active by tag names
  let tagName = elem.tagName.toLowerCase();
  toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-tag-name="${tagName}"]`)[0];
  if(toolbarButton) {
    toolbarButton.classList.add('active');
  }

  // active by text-align
  let textAlign = elem.style.textAlign;
  toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-style="textAlign:${textAlign}"]`)[0];
  if(toolbarButton) {
    toolbarButton.classList.add('active');
  }

  return parentTagActive(elem.parentNode);
}
Enter fullscreen mode Exit fullscreen mode

3.5 Remove formatting when pasting text (paste event)

When a user pastes something into the text editor, all formatting should be removed from this text, otherwise it can lead to unsightly formatting and complete design chaos. For this we register the paste event.

// add paste event
visuellView.addEventListener('paste', pasteEvent);
Enter fullscreen mode Exit fullscreen mode

The pasteEvent() function is then executed, which prevents normal pasting, gets the content from the user’s clipboard as plain text, and pastes it into our editor.

function pasteEvent(e) {
  e.preventDefault();

  let text = (e.originalEvent || e).clipboardData.getData('text/plain');
  document.execCommand('insertHTML', false, text);
}
Enter fullscreen mode Exit fullscreen mode

3.6 Insert p tag as line break

Another improvement is to automatically insert a <p> tag as soon as the user presses Enter. For this we register the keypress event.

// add paragraph tag on new line
contentArea.addEventListener('keypress', addParagraphTag);
Enter fullscreen mode Exit fullscreen mode

The addParagraphTag() function is called. This checks whether the Enter key was pressed (keycode 13). Then the current block is automatically formatted as a <p>-tag if the current element is not a list element (<li>-tag).

function addParagraphTag(evt) {
  if (evt.keyCode == '13') {

    // don't add a p tag on list item
    if(window.getSelection().anchorNode.parentNode.tagName === 'LI') return;
    document.execCommand('formatBlock', false, 'p');
  }
}
Enter fullscreen mode Exit fullscreen mode

3.7 Full JavaScript Code

➑️ Check out the full code of the JavaScript file here

4. Conclusion

As you can see now, you can program your own WYSIWYG editor relatively easily and style and program it according to your ideas. If you liked this post, I would be happy if you support my blog by visiting it again. πŸ™‚

On this page I’m also using this WYSIWYG Editor for the WordPress Comments. Check out the link to see how easy this works!

Top comments (10)

Collapse
 
deathshadow60 profile image
deathshadow60 • Edited

I see a number of issues with this, but I think the biggest is your use of hooking SPAN with scripting for the image buttons, instead of anchor or button. Why is this a problem?

Because span aren't keyboard navigable. This is a problem people with the WYSIWYG mentality often overlook, is not everyone is using touch or a mouse.

Admittedly, navigating with the keyboard to the buttons would defocus the area being edited, but it's still not a habit to get into, given the basic accessibility violation that can create.

it's also kind of a wonk in 2022 to be using external images instead of static SVG in the CSS and/or webfonts. That would be a huge improvement.

All that said, GIANT thumbs up for writing this using vanilla code, instead of some rubbish framework. That way anyone can use it without screwing around with any extra includes, build steps, or the possibility of conflicts.

Though those querySelectorAll when pulling an ID is a bit screwy.

Collapse
 
codingjlu profile image
codingjlu

So why build your own WYSIWYG editor? Go use something like Quill or TinyMCE and don't worry about a thing. It's less dirty code anyways. But great job for creating your own vanilla editor, seems decent.

Collapse
 
webdeasy profile image
webdeasy.de

Hey, thanks for your comment! That's right, I didn't think about accessibility in detail when creating this editor. But I will "fix" this as soon as possible.
Thanks for your feedback :)

Collapse
 
anuradha9712 profile image
Anuradha Aggarwal

Nice article!!

Collapse
 
webdeasy profile image
webdeasy.de

Thank you πŸ˜‡

Collapse
 
qymmore profile image
Sarah Qym

This is awesome. I'll definitely be trying to follow along this tutorial to build my own editor

Collapse
 
webdeasy profile image
webdeasy.de

Glad to inspire you! Tell me how it worked out :)

Collapse
 
qymmore profile image
Sarah Qym

Oh for sure!

Collapse
 
mhasan profile image
Mahmudul Hasan

Nice article

Collapse
 
webdeasy profile image
webdeasy.de

Thanks!