Skip to content

Instantly share code, notes, and snippets.

@stefanocudini
Created April 28, 2012 18:36
Show Gist options
  • Select an option

  • Save stefanocudini/2521177 to your computer and use it in GitHub Desktop.

Select an option

Save stefanocudini/2521177 to your computer and use it in GitHub Desktop.
select text range
function createSelection(start, end, field) {
if ( field.createTextRange ) {
/*
IE calculates the end of selection range based
from the starting point.
Other browsers will calculate end of selection from
the beginning of given text node.
*/
var newend = end - start;
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", newend);
selRange.select();
}
/* For the other browsers */
else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
}
field.focus();
}
/*
Usage
*/
var target = document.getElementById("target-input-or-textarea");
createSelection(10, 20, target);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment