JavaScript document.execCommand() Web Method

The JS document.execCommand() method is quite interesting. It can be used to execute certain commands to play with an editable region that is achieved either via the contenteditable attribute or when the HTML document (of the main window or some iframe window) has been switched to designMode using this code:

document.designMode = 'on'; // or 'off'
// or for an iframe
iframeNode.contentDocument.designMode = 'on'; // or 'off')

Infact try the first snippet right in dev tools and see what happens 🙂

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

So what sort of commands are we talking about ? Well commands that can make a document selection bold, italic or cut/copy it. There are other commands as well to insert new elements like an image (at the caret position). The execCommand method accepts three arguments:

  • commandName – String representing a command name.
  • showDefaultUI – Boolean indicating whether to display any supporting user interface.
  • value – String representing a value which is basically an argument for the command name (will clarify in examples below).

Let’s see a piece of code which will help us understand how the method can be used:

<div id="wysiwyg" style="margin: 20px;">
  <input type="button" value="B" onclick="document.execCommand('bold', false, '');" style="font-weight: bold;" />
  
  <input type="button" value="I" onclick="document.execCommand('italic', false, '');" style="font-style: italic;" />
  
  <input type="button" value="U" onclick="document.execCommand('underline', false, '');" style="text-decoration: underline;"/>
  
  <input type="button" value="delete" onclick="document.execCommand('delete', false, '');" />
  
  <input type="button" value="link" onclick="document.execCommand('createLink', false, 'http://google.com');" />
  
  <input type="button" value="image" onclick="document.execCommand('insertImage', false, 'http://lorempixel.com/40/20/sports/')" />
  
  <div contenteditable="true">Lorem Ipsum is simply dummy text of the printing and typesetting industry</div>
</div>

Try this piece of code at CSSDeck to quickly see how on selecting the text in the contenteditable div and clicking one of the buttons, the execCommand() leads to a change in the HTML (and hence the UI) of the div. One could possibly use this technique to make a simple wysiwyg editor for his web application. Don’t forget to check out MDN for a list of all the available commands.

If you come up with some interesting use cases for this method, then feel free to share in the comments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *