Creating a Selection (^) ❘ 473
Again, you check that the $(this).data() function returned valid information, that it contains
a format member, and fi nally that the HTML document object supports the execCommand function,
which is a shortcut for JavaScript to tell the browser to handle specifi c functions using its
native features.
document.execCommand(data.format, false, null);
$('div#container').focus();
After these checks pass, you send the format value to the document.execCommand function with the
additional parameters false (no user interface prompt for the user) and null (no value needed for
bold, italic, or underline). Finally, because the button click removed focus from the editable element,
you send the focus back to the editable element.
The
Creating a Selection
While working with the previous examples, you might have noticed the ability to change existing
content by selecting it in the editable element. JavaScript offers the ability to work with selections,
including options for creating a selection programmatically, storing information about a current
selection, and restoring a selection that has been deselected. The next set of example code is fairly
large to account for these cases, but each is discussed in turn.Begin with the example markup (Example 21-3.html):
<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='content-type'
content='application/xhtml+xml; charset=utf-8' />
<meta http-equiv='content-language' content='en-us' />
<meta charset='utf-8' />
<title>WYSIWYG Editor 3</title>
<link href='Example 22-3.css' rel='stylesheet' />