Javascript: contenteditable div introduction

contenteditable divs are more powerful versions of <textarea>s because you can insert HTML into them.

<div contenteditable="true">
</div>

This would be an empty div. Let's change that with CSS

div[contenteditable] {
  display: inline-block;
  background: white;
  min-width: 10px;
  border: 1px solid black;
}

Now you can edit the div and it will expand as you type. (An advantage over <textarea>s)


As you type lines and press enter the content of the <div> will look like this:

<div contenteditable="true">
  <div>I am line one</div>
  <div>I am line two</div>
  <div>I am line three</div>
</div>

Let's put our contenteditable div in a bigger div that has buttons:

<div>
  <button id="button1">😀</button>
  <div contenteditable="true">
  </div>
</div>

When the button is pressed we'll turn on the documents's designMode and use document.execCommand().

document.execCommand() has three parameters: the command, a false parameter and the content. We'll use document.execCommand('insertHTML, false, "😃")`.

document.querySelector("#button1").onclick = _ => {
  document.designMode = "on"
  document.execCommand("insertHTML", false, "<span>😀</span>")
  document.designMode = "off"
}

Our inserted HTML is very simple. You can insert anything you want; images, youtube videos, audio files.

javascript
I've removed disqus comments
Instead, press this
to express thanks
So far, 0 people have pressed the octopus