Web Development with jQuery®

(Elliott) #1

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 element, so the indicated pattern is used as a shortcut to the selected
item’s value, which is then passed as the data value.
this.selectedIndex = 0 ;
For the purposes of this simple editor, the blank item at the top of each list is then selected.
Although it does add the inconvenience of not seeing the last selected item, it also prevents some
possible confusion. Without this line, a user might expect that you would detect the font name and
size when you select text in the editable element.


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' />

http://www.it-ebooks.info

Free download pdf