JavaScript – Get selected highlighted text

The code:

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
<!DOCTYPE html>
<html>
<head>
<script>
function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;
  // IE version
  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  // Mozilla version
  else if (textComponent.selectionStart != undefined)
  {
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
  }
  alert("You selected: " + selectedText);
}
</script>
</head>
<body>
 
Enter your name: <input type="text" id="Editor">
<button onclick="ShowSelection()">ShowSelection()</button>
 
</body>
</html>

My official WebSite >