1 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
---|
2 | <html xmlns="http://www.w3.org/1999/xhtml"> |
---|
3 | <head> |
---|
4 | <title>Collapsed Element Selection</title> |
---|
5 | <script type="text/javascript"> |
---|
6 | |
---|
7 | // The code inside window.onload has nothing to do with the issue, |
---|
8 | // so it can be ignored. |
---|
9 | window.onload = function() |
---|
10 | { |
---|
11 | document.designMode = 'on' ; |
---|
12 | |
---|
13 | // For Safari and Opera, we must ensure the focus. |
---|
14 | if ( (/safari/i).test( navigator.userAgent ) ) |
---|
15 | document.documentElement.focus() ; // Safari |
---|
16 | else |
---|
17 | window.focus() ; // Opera. |
---|
18 | |
---|
19 | MoveSelection() ; |
---|
20 | } |
---|
21 | |
---|
22 | // Here is the function to be analyzed. |
---|
23 | function MoveSelection() |
---|
24 | { |
---|
25 | // Get our target empty element. |
---|
26 | var el = document.getElementsByTagName( 'b' )[0] ; |
---|
27 | |
---|
28 | // This is the hack for Firefox and Opera to make the cursor blinking |
---|
29 | // properly inside the empty element. It would be ok if it would work for |
---|
30 | // Safari too, but ideally it should not be needed. |
---|
31 | el.appendChild( document.createTextNode('') ) ; |
---|
32 | |
---|
33 | // Create a range inside the element. |
---|
34 | var range = document.createRange() ; |
---|
35 | range.setStart( el, 0 ) ; |
---|
36 | range.setEnd( el, 0 ) ; |
---|
37 | |
---|
38 | // Move the selection to the range. |
---|
39 | var selection = window.getSelection() ; |
---|
40 | selection.removeAllRanges() ; |
---|
41 | selection.addRange( range ) ; |
---|
42 | } |
---|
43 | |
---|
44 | </script> |
---|
45 | </head> |
---|
46 | <body> |
---|
47 | <h1> |
---|
48 | Selection inside empty element |
---|
49 | </h1> |
---|
50 | <p> |
---|
51 | This is an editable document. When loading this page, the caret should be blinking |
---|
52 | inside the following brackets. Start typing. The text must be <strong>bold</strong>. |
---|
53 | </p> |
---|
54 | <p> |
---|
55 | [<b></b>]<br /> |
---|
56 | [<b></b>] |
---|
57 | </p> |
---|
58 | <hr /> |
---|
59 | <p> |
---|
60 | An important aspect to consider is that, if you don't type anything when loading |
---|
61 | the page, but instead use the keyboard to change the caret position, there should |
---|
62 | be no way to move inside the empty element again with the mouse or the keyboard, |
---|
63 | which means that it will remain empty forever. This is the desired behavior. |
---|
64 | </p> |
---|
65 | <p> |
---|
66 | This page is not intended to be compatible with IE, as there are several hacks to |
---|
67 | make it work there. It should instead work properly with Firefox, Opera and Safari. |
---|
68 | </p> |
---|
69 | </body> |
---|
70 | </html> |
---|