JavaScript window.getSelection() Method
You are Here:
JavaScript window.getSelection() Method
The window.getSelection()
method returns an object representing the range of text selected by the user or the current position of the caret.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<input type="text" onselect="myFunction()" value="Select some text">
<p id="point"></p>
<script>
var x = document.getElementById("point");
function myFunction() {
var selObj = window.getSelection();
x.innerHTML = "You Selected: <strong>"+ selObj+"</strong>";
}
</script>
</body>
</html>
Syntax
window.getSelection()
Return Value
Value | Explanation |
---|---|
Object | A Object, representing the range of text selected by the user. |
Creating Text Editor
In the following example, we will convert the user-selected text to uppercase.
Note: This example is good enough to give you an idea about how to create your own text editor.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<input type="text" onselect="myFunction()" value="select some text">
<p id="point"></p>
<script>
var x = document.getElementById("point");
function myFunction() {
var myVal = document.getElementsByTagName("input")[0].value
var len = myVal.length;
var activeEl = document.activeElement;
var selStart = activeEl.selectionStart;
var selEnd = activeEl.selectionEnd;
var mySelect = getSelection().toString();
var myChange = mySelect.toUpperCase();
var myData = myVal.slice(0, selStart)+""+myChange+""+myVal.slice(selEnd, len);
x.innerHTML = myData;
}
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.