You are here: Reference > JavaScript > client-side > selection and ranges > methods > execCommand (document, TextRange, ...)
execCommand method (document, TextRange, ...)
Allows running commands on certain objects.
The execCommand is one of the root methods of the rich-text editing feature of browsers.
The execCommand method works differently in different browsers, the commands are only executable for editable elements in Firefox, Google Chrome and Safari, while in Internet Explorer and Opera they can be used in editable and non-editable elements also.
The code generated by the execCommand method is different in browsers.
Internet Explorer uses HTML tags, Firefox, Google Chrome and Safari generate inline styles and Opera sometimes uses HTML tags, sometimes styles.
An element can be made editable with the contentEditable property.
If you want to make the entire document editable, use the designMode property or the contentEditable property for the body element.
Note: Firefox only supports the contentEditable property from version 3.
For example, if the 'bold' command is executed on a non-bold text,
- Internet Explorer and Opera generate a strong element around it,
- Firefox, Google Chrome and Safari generate a span element around it and set the fontWeight style property of the span element to 'bold'. If an element exists around the non-bold text, then Firefox, Google Chrome and Safari set the fontWeight style property of this element to 'bold'.
It can cause a problem if the execCommand method is executed on content that was previously generated by another browser.
For example, in case of forums when the author tries to edit his/her post in a different browser than it was previously sent from.
In that case, for example, if the 'bold' command is executed in Internet Explorer on a bold text that was previously created by the execCommand method in Firefox, then Internet Explorer cannot remove the bold style.
Example 4 shows a solution in Firefox, Opera, Google Chrome and Safari for changing the color of the selected text.
Other text manipulation methods can be implemented similarly.
Use the queryCommandSupported method to detect whether a command is supported by the execCommand method.
The use of a non-supported command for the execCommand method raises an exception.
Syntax:
You can find the related objects in the Supported by objects section below.
Parameters:
Required. A case-insensitive string that specifies the name of the command. See command identifiers for more information. | |||||||||||||||||||||||
Required in Firefox and Opera, optional in Internet Explorer, Google Chrome and Safari. Boolean that indicates whether a user interface needs to be displayed or not.
One of the following values:
|
|||||||||||||||||||||||
Required in Firefox and Opera, optional in Internet Explorer, Google Chrome and Safari. Specifies a parameter value for the command. The possible values depend on the command. Use null if no value is needed. |
Return value:
Boolean. One of the following values:
There was an error while processing the command. | |
The command was successful. |
Example HTML code 1:
This example illustrates the use of the execCommand method:
|
||||
<head> <script type="text/javascript"> function SetToBold () { document.execCommand ('bold', false, null); } </script> </head> <body> <div contenteditable="true" onmouseup="SetToBold ();">Select a part of this text!</div> </body> |
||||
|
||||
Did you find this example helpful?
|
Example HTML code 2:
This example implements the previous example so that it works in older browsers as well:
|
|||||
<head> <script type="text/javascript"> var editorDoc; function InitEditable () { var editor = document.getElementById ("editor"); editorDoc = editor.contentWindow.document; var editorBody = editorDoc.body; // turn off spellcheck if ('spellcheck' in editorBody) { // Firefox editorBody.spellcheck = false; } if ('contentEditable' in editorBody) { // allow contentEditable editorBody.contentEditable = true; } else { // Firefox earlier than version 3 if ('designMode' in editorDoc) { // turn on designMode editorDoc.designMode = "on"; } } } function ToggleBold () { editorDoc.execCommand ('bold', false, null); } </script> </head> <body onload="InitEditable ();"> First, write and select some text in the editor. <br /> <iframe id="editor" src="editable.htm"></iframe> <br /><br /> You can toggle the bold/normal state of the selected text with this button: <br /> <button onclick="ToggleBold ();">Bold</button> </body> |
|||||
|
|||||
Did you find this example helpful?
|
Example HTML code 3:
This example implements a simple WYSIWYG (What You See Is What You Get) editor:
|
|||||
<head> <script type="text/javascript"> var editorDoc; function InitEditable () { var editor = document.getElementById ("editor"); if (editor.contentDocument) editorDoc = editor.contentDocument; else editorDoc = editor.contentWindow.document; var editorBody = editorDoc.body; // turn off spellcheck if ('spellcheck' in editorBody) { // Firefox editorBody.spellcheck = false; } if ('contentEditable' in editorBody) { // allow contentEditable editorBody.contentEditable = true; } else { // Firefox earlier than version 3 if ('designMode' in editorDoc) { // turn on designMode editorDoc.designMode = "on"; } } } function ToggleBold () { editorDoc.execCommand ('bold', false, null); } function ToggleItalic () { editorDoc.execCommand ('italic', false, null); } function SetRed () { editorDoc.execCommand ('foreColor', false, "#ff0000"); } function Delete () { editorDoc.execCommand ('delete', false, null); } </script> </head> <body onload="InitEditable ();"> First, write and select some text in the editor. <br /> <iframe id="editor" src="editable.htm"></iframe> <br /><br /> You can use the following buttons to change the appearance of the selected text: <br /><br /> <button onclick="ToggleBold ();">Bold</button> <button onclick="ToggleItalic ();">Italic</button> <button onclick="SetRed ();">Set to red</button> <button onclick="Delete ();">Delete</button> </body> |
|||||
|
|||||
Did you find this example helpful?
|
Example HTML code 4:
This complex example modifies the color of the selected text in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, similarly to the execCommand when it is invoked with the 'ForeColor' command. The example uses the selectionRange and Range objects to implements this functionality. The advantage of this solution is the browser-independently generated HTML code.
|
||||
<head> <script type="text/javascript"> function GetNextLeaf (node) { while (!node.nextSibling) { node = node.parentNode; if (!node) { return node; } } var leaf = node.nextSibling; while (leaf.firstChild) { leaf = leaf.firstChild; } return leaf; } function GetPreviousLeaf (node) { while (!node.previousSibling) { node = node.parentNode; if (!node) { return node; } } var leaf = node.previousSibling; while (leaf.lastChild) { leaf = leaf.lastChild; } return leaf; } // If the text content of an element contains white-spaces only, then does not need to colorize function IsTextVisible (text) { for (var i = 0; i < text.length; i++) { if (text[i] != ' ' && text[i] != '\t' && text[i] != '\r' && text[i] != '\n') return true; } return false; } function ColorizeLeaf (node, color) { if (!IsTextVisible (node.textContent)) return; var parentNode = node.parentNode; // if the node does not have siblings and the parent is a span element, then modify its color if (!node.previousSibling && !node.nextSibling) { if (parentNode.tagName.toLowerCase () == "span") { parentNode.style.color = color; return; } } // Create a span element around the node var span = document.createElement ("span"); span.style.color = color; var nextSibling = node.nextSibling; parentNode.removeChild (node); span.appendChild (node); parentNode.insertBefore (span, nextSibling); } function ColorizeLeafFromTo (node, color, from, to) { var text = node.textContent; if (!IsTextVisible (text)) return; if (from < 0) from = 0; if (to < 0) to = text.length; if (from == 0 && to >= text.length) { // to avoid unnecessary span elements ColorizeLeaf (node, color); return; } var part1 = text.substring (0, from); var part2 = text.substring (from, to); var part3 = text.substring (to, text.length); var parentNode = node.parentNode; var nextSibling = node.nextSibling; parentNode.removeChild (node); if (part1.length > 0) { var textNode = document.createTextNode (part1); parentNode.insertBefore (textNode, nextSibling); } if (part2.length > 0) { var span = document.createElement ("span"); span.style.color = color; var textNode = document.createTextNode (part2); span.appendChild (textNode); parentNode.insertBefore (span, nextSibling); } if (part3.length > 0) { var textNode = document.createTextNode (part3); parentNode.insertBefore (textNode, nextSibling); } } function ColorizeNode (node, color) { var childNode = node.firstChild; if (!childNode) { ColorizeLeaf (node, color); return; } while (childNode) { // store the next sibling of the childNode, because colorizing modifies the DOM structure var nextSibling = childNode.nextSibling; ColorizeNode (childNode, color); childNode = nextSibling; } } function ColorizeNodeFromTo (node, color, from, to) { var childNode = node.firstChild; if (!childNode) { ColorizeLeafFromTo (node, color, from, to); return; } for (var i = from; i < to; i++) { ColorizeNode (node.childNodes[i], color); } } function ColorizeSelection (color) { if (window.getSelection) { // all browsers, except IE before version 9 var selectionRange = window.getSelection (); if (selectionRange.isCollapsed) { alert ("Please select some content first!"); } else { var range = selectionRange.getRangeAt (0); // store the start and end points of the current selection, because the selection will be removed var startContainer = range.startContainer; var startOffset = range.startOffset; var endContainer = range.endContainer; var endOffset = range.endOffset; // because of Opera, we need to remove the selection before modifying the DOM hierarchy selectionRange.removeAllRanges (); if (startContainer == endContainer) { ColorizeNodeFromTo (startContainer, color, startOffset, endOffset); } else { if (startContainer.firstChild) { var startLeaf = startContainer.childNodes[startOffset]; } else { var startLeaf = GetNextLeaf (startContainer); ColorizeLeafFromTo (startContainer, color, startOffset, -1); } if (endContainer.firstChild) { if (endOffset > 0) { var endLeaf = endContainer.childNodes[endOffset - 1]; } else { var endLeaf = GetPreviousLeaf (endContainer); } } else { var endLeaf = GetPreviousLeaf (endContainer); ColorizeLeafFromTo (endContainer, color, 0, endOffset); } while (startLeaf) { var nextLeaf = GetNextLeaf (startLeaf); ColorizeLeaf (startLeaf, color); if (startLeaf == endLeaf) { break; } startLeaf = nextLeaf; } } } } else { // Internet Explorer before version 9 alert ("Your browser does not support this example!"); } } </script> </head> <body> Select some content on this page and use the buttons below to colorize the selected text.<br /><br /> <button onclick="ColorizeSelection ('#FF0000');">Set color to red!</button> <button onclick="ColorizeSelection ('#0000FF');">Set color to blue!</button> <br /> <div>Some text for selection</div> <div><b>Some bold text for selection.</b></div> </body> |
||||
|
||||
Did you find this example helpful?
|
Supported by objects:
Related pages:
contentEditable
designMode
queryCommandEnabled
queryCommandIndeterm
queryCommandState
queryCommandSupported
queryCommandText
queryCommandValue
designMode
queryCommandEnabled
queryCommandIndeterm
queryCommandState
queryCommandSupported
queryCommandText
queryCommandValue
External links:
User Contributed Comments