Text Selection API: HTML5

Advertisement:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE html>
<html>
<head>
<title>selection of Text: HTML5</title>
<script src="myScript.js"></script>
</head>
<body>
 
<label for="name">Name: </label>
 <input type="text" id="name" value="Satish, CEO Technotip.com"/>
<button onclick="txtSelect()">Select</button>
 
</body>
</html>

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

1
2
3
4
5
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

1
2
3
4
5
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

1
2
3
4
5
6
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

1
2
3
4
5
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


You need to a flashplayer enabled browser to view this YouTube video

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



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

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
function txtSelect()
{
	var input = document.getElementById("name");
	    input.selectionStart = 10;
 
            alert(input.selectionStart);
}

This output’s value 10.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *