Some code I wrote a while back (well, collated is probably the more apt term) to simplify selecting text, unselecting text, and placing the cursor using javascript.
l is a shortcut for console.log.
/* Class: TheDom
Class to manage the manipulation and output of assorted DOM and DOM-related
elements. Most methods are offered as static methods.
Methods:
TheDom.getSelectedText(el)
TheDom.selectRange(el, p1, p2)
TheDom.placeCursor(el, pos)
TheDom.insertString(insert, wrapper, pt1, pt2)
TheDom.wrapInTag(text, tag, id, class, style)
*/
var TheDom = {};
// arguments: el (DOM element)
TheDom.getSelectedText = function(el)
{
selected = [false, 0, 0]; // returns array: [ selected text, start_pos, end_pos ]
l('getSelectedText from DOM [type,id]:', el.tagName, ',', el.id );
// get start/end
var s1 = 0; var s2 = 0;
if ( typeof document.selection != 'undefined' )
{
var r = document.selection.createRange();
s1 = r.start;
s2 = r.end;
}
else if ( typeof el.selectionStart != 'undefined' )
{
s1 = el.selectionStart;
s2 = el.selectionEnd;
}
else
{
l('getSelectedText handle not found');
return selected;
}
// trim selection
while ( s2 < s1 && el.value.charAt(s2-1) == ' ' ) s2--;
// no selection
if ( s2 - s1 == 0 ) sel_text = '';
if ( s2 - s1 > 0 ) return selected;
sel_text = el.value.substring(s1, s2);
l('getSelectedText returning:', sel_text, s1, s2);
return [sel_text, s1, s2];
};
// arguments: el [DOM element], p1 [int], p2 [int]
TheDom.selectRange = function(el, p1, p2)
{
// return void
l('selectRange:', el, p1, p2);
if(el.setSelectionRange)
{
el.focus();
el.setSelectionRange(p1,p2);
}
else if(el.createTextRange)
{
range=el.createTextRange();
range.collapse(true);
range.moveEnd('character',p2);
range.moveStart('character',p1);
range.select();
}
else
{
l('selectRange: no selection handle');
}
};
// arguments: el [DOM object], pos [int]
TheDom.placeCursor = function(el, pos)
{
l('placeCursor:',el.id, pos);
TheDom.selectRange(el, pos, pos);
};
// arguments: insert [string], wrapper [string], pt1 [int], pt2 [int]
TheDom.insertString = function(insert, wrapper, pt1, pt2)
{
var new_test = ''; // return
l('insertString:', insert, wrapper, pt1, pt2);
if ( pt2 == undefined ) pt2 = pt1;
new_text = wrapper.substring(0, pt1) + insert + wrapper.substr(pt2);
return new_text;
};
// arguments: text, tag name, [tag id, class, style] [str]
TheDom.wrapInTag = function(text, tag, id, class, style)
{
var wrap = ''; // return
l('wrapInTag:', text, tag, id, class, style);
var id = ( id != undefined ) ? ' id="'+id+'"' : '';
var class = ( class != undefined ) ? ' class="'+class+'"' : '';
var style = ( style != undefined ) ? ' id="'+style+'"' : '';
var t1 = '>' + tag + id + class + style + '<';
var t2 = '</' + tag + '<';
wrap = t1 + text + t2;
l('wrapInTag return:', wrap);
return wrap;
};
Labels: javascript