Text Selection API: HTML5

Before HTML5 we were using select() method to select the entire text/string present in the input field. We did not have more control to specify the selection start and end points ourselves. With HTML5 text selection API’s we could specify selection start and end points.

HTML file
index.html

< !DOCTYPE html>


selection of Text: HTML5





 




Here we have a input box with some pre-populated text/string inside it. We also have a button, clicking on which we invoke txtSelect() method.

JavaScript file: select() method
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.select();
}

We select the input field by it’s id. Then, by using select() method we select the entire text present inside the input field. This is the old school method we used to select the text even before HTML5.

JavaScript file: selectionStart property
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.selectionStart = 3;
}

selectionStart is a HTML5 property that sets or gets the selection start points.

JavaScript file: selectionEnd property
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.selectionStart = 3;
     input.selectionEnd   = 15;
}

This specifies the selection start and end points. Hence selects the text between these points. selectionEnd is a HTML5 property which sets or gets the selection end point.

JavaScript file: setSelectionRange() method
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.setSelectionRange(3, 20);
}

setSelectionRange(start, end) is a HTML5 method that sets the selection start and end point. In above case, text is selected from the index 3 and 20.

Text Selection API: HTML5



YouTube Link: https://www.youtube.com/watch?v=P9P4ZX8c31E [Watch the Video In Full Screen.]



You can also try …
JavaScript file: getting selectionStart value
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.setSelectionRange(3, 20);

            alert(input.selectionStart);
}

This output’s value 3.

JavaScript file: getting selectionStart value
myScript.js

function txtSelect()
{
 var input = document.getElementById("name");
     input.selectionStart = 10;

            alert(input.selectionStart);
}

This output’s value 10.