code of javascript to select partial text in a div element


Some times we need mechanisms to select(highlight) partial text in a div or td element, lets say on click of a button. So that visitor just right click on selected text and copy the text to paste it anywhere else.

The code I am going to publish selects the div elements on the base of starting character and length of div text.

Lets say if you want to select first 500 characters in div you will provide the "start" argument as 0 and length as 500.

Similarly, you can choose to select(highlight) the text form 100th character to 600th in the div. In this case you will provide the "start" as 100 and "length" as 600. First argument will be id of div element in which text is to be select.

Lets go to the actual code now. here goes the select text function.

function selectText(ID, start, length)
{

if (document.selection)
{
//Code for IE and few other
document.selection.empty();
var textC = document.getElementById(ID);
var div = document.body.createTextRange();
div.moveToElementText(textC);
div.setEndPoint("EndToEnd", div);
div.moveStart('character', start);
if(length + start>textC.innerHTML.length)
length=textC.innerHTML.length-start;

div.moveEnd('character', -(textC.innerHTML.length - start - length));
div.select();
}
else
{
//code for FF and few other
window.getSelection().removeAllRanges();
var textC = document.getElementById(ID);
while ( textC.hasChildNodes() ) textC = textC.childNodes[0];
var div = document.createRange();

div.setStart(textC, start);
if (start+length > textC.length) length = textC.length - start;
div.setEnd(textC, start+length);

window.getSelection().addRange(div);
}

return false;

}

Now this is how we will implement this in HTML for lets say selecting first 500 characters in this case.


Some text here to be selected...



Above is the way I am calling the code you can always call function on different event according to your requirements.

Enjoy!!!

Posted in |