DEV Community

Cover image for How to build your own WYSIWYG Editor
Sai gowtham
Sai gowtham

Posted on

How to build your own WYSIWYG Editor

Have you seen WYSIWYG editors Today I'm showing the simple version of WYSIWYG editor.

If you're familiar with HTML and JavaScript then you're good to go.

So let's start our simple version
I'm not explaining everything but Important things

first, we need to add a contentEditable attribute to our HTML element

 <div class="editor" contenteditable>
      <h1>Simple Html editor</h1>
      <p>Good to start</p>
    </div>

Now, div element is editable and our HTML document exposes execCommand.

Let's see what is execCommand

document.execCommand(cmd,defaultUI,value);

execCommand needs three arguments

cmd : It means we have to tell which command needs to execute.
example:'bold' commandslist

defaultUI :it is boolean whether default user interface is shown or not.

value : We need to add value argument to some commands.
example: In createLink cmd, we need to add a value it refers to href attribute in the link.

So lets make it use of execCommand in practice

Now I'm creating button HTML element and attached an event listener to it.

  <button class="tool-items fa fa-bold" 
  onclick="document.execCommand('bold', false, '');">
 </button>

Now we are only built bold command Check out full version below.

Top comments (7)

Collapse
 
krati1812 profile image
Krati Agarwal

Nice post. Thanks for sharing.

Collapse
 
tonyfrenzy profile image
tony

Brilliant!

Collapse
 
jaradc profile image
jaradc

Any thoughts regarding the warning on this page about execCommand ?
w3c.github.io/editing/ActiveDocume...

Collapse
 
vsvad profile image
vsvad
Collapse
 
le_newtype profile image
Nicholas ―M―

I had no idea about execCommand. I'll play around with this later; thank you for sharing!

Collapse
 
joaoeudes7 profile image
João Eudes Lima

Good!

Collapse
 
carloslfu profile image
Carlos Galarza

Good post!