-
Notifications
You must be signed in to change notification settings - Fork 0
/
setSelectionOnPaste.html
64 lines (53 loc) · 1.61 KB
/
setSelectionOnPaste.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<html>
<head>
<title>IE11 Fails to Set Selection on Paste Event</title>
<style>
p#input {
background-color: #E3E3E3;
font-family: monospace;
font-size: 50px;
margin: 0;
width: 500px;
white-space: nowrap;
}
</style>
</head>
<body>
<h1>IE11 Fails to Set Selection on Paste Event</h1>
<p>Steps to reproduce:</p>
<ol>
<li>Load in IE11</li>
<li>Select the "k" character</li>
<li>Right Click > Paste (DON'T USE CTRL+V) paste something</li>
<li>Notice the caret doesn't go to the 1 position (between a and b)</li>
<li>Tap a keybaord key, notice the caret does move to the 1 position</li>
</ol>
<p>Workaround:</p>
<p>Use a <code>setTimeout( function(){}, 0 )</code> when setting the caret position within an onpaste handler in IE.</p>
<div class="wrapper">
<p id="input" contenteditable="true" class="editable-region" onkeyup="handle( event )" onpaste="handle( event )">abcdefghijk</p>
</div>
<script type="text/javascript">
function handle( event ) {
event.preventDefault();
// Workaround for IE11 is to wait for the stack to unwind:
//setTimeout(function(){
setCaretPosition( 1, 1 );
//},0);
}
function setCaretPosition( start, end ){
var input = document.getElementById( 'input' );
// set the selection
if ( document.createRange && window.getSelection ){
var range = document.createRange();
range.selectNodeContents( input );
range.setStart( input.childNodes[ 0 ], start );
range.setEnd( input.childNodes[ 0 ], end );
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange( range );
}
}
</script>
</body>
</html>