I've just started using a contentEditable, and have not found much comprehensive information on it.
I noticed that in Chrome, I can make words bold/italic by pressing CTRL-B and CTRL-I.
Is this possibly going to be the intended behavior in other browsers? This, for instance, works in Chrome:
<div class="container" id="typer" onclick="this.contentEditable='true';">
/
I'm wondering if I can read this formatting, in order to save the user's edits? Also, can I create a Bold button and Italic button that will trigger CTRL-B and CTRL-I? Or would I need to depend on the user pressing CTRL-B and CTRL-I (which means providing them a note telling them)?
I've just started using a contentEditable, and have not found much comprehensive information on it.
I noticed that in Chrome, I can make words bold/italic by pressing CTRL-B and CTRL-I.
Is this possibly going to be the intended behavior in other browsers? This, for instance, works in Chrome:
<div class="container" id="typer" onclick="this.contentEditable='true';">
http://jsfiddle.net/uk6DA/15/
I'm wondering if I can read this formatting, in order to save the user's edits? Also, can I create a Bold button and Italic button that will trigger CTRL-B and CTRL-I? Or would I need to depend on the user pressing CTRL-B and CTRL-I (which means providing them a note telling them)?
Share Improve this question edited Dec 12, 2014 at 15:12 j0k 22.8k28 gold badges81 silver badges90 bronze badges asked Aug 13, 2012 at 13:40 DaveDave 5,0296 gold badges51 silver badges75 bronze badges3 Answers
Reset to default 18This is standard in all major browsers. There are also programmatic equivalents of the keyboard shortcuts available via document.execCommand()
in all major browsers, although in 2022 this seems to be on the way out. For now, bold and italic commands, for example, can executed as follows:
document.execCommand("Bold", false, null);
document.execCommand("Italic", false, null);
However, the mark-up generated varies between browsers. For example, variations for bold include <b>foo</b>
, <strong>foo</strong>
and <span style="font-weight: bold">foo</span>
.
References:
- MSDN, list of commands
- MDN (Mozilla)
Short answer 'yes'. You might find this article interesting. Many a' developer have gone down this route. If you want a nice wysiwyg editor, there are many to choose from.
On to your question: yes you can read the formatting. Try an innerHTML on the element and you'll find <b>
tags around your bolds and <i>
around your italics. Also - in the article I shared, you'll find out how to create a button that will bold. Hope this helps!
You can see which browsers support the contentEditable feature here:
https://caniuse.com/#search=contenteditable
And as Tim Down said, you can call the document.execCommand()
to bold or italicize things.
However, the keyboard shortcuts cannot be expected to be the same in all browsers, browser shortcuts are not standardized. CTRL-B for example is the bookmark shortcut in FireFox.