Forum Moderators: open

Message Too Old, No Replies

problem with javascript selection manipulation in ie

         

Skier88

7:55 pm on Oct 5, 2010 (gmt 0)

10+ Year Member



I am writing a text editor with buttons that, when clicked, surround the selection with their tag then move the cursor to the end of the closing tag. The first part works everywhere I've tested, but I can't figure out how to move the cursor in IE. Googling turns up no shortage of seemingly related results, but I honestly can't make sense of them. Since I'm already manipulating the selection, it seems like a line or two of code should be able to move the cursor. Here's what I have now (variable ie is globally defined).

function tag(obj,tag)
{
var start,end,pos,range;
if (ie)
{
obj.focus();
range=document.selection.createRange();
if(range=='')
return false;
if (range.parentElement()!==obj)
return false;
if (typeof range.text==='string')
document.selection.createRange().text='['+tag+']'+range.text+'[/'+tag+']';
//ie cursor code goes here
}
else
{
start=obj.selectionStart;
end=obj.selectionEnd;
if(start===end)
{
obj.focus();
return false;
}
obj.value=obj.value.substring(0,start)+'['+tag+']'+obj.value.substring(start,end)+'[/'+tag+']'+obj.value.substring(end);
obj.focus();
pos=end+tag.length*2+5;
obj.setSelectionRange(pos,pos);
}
return false;
}


Thanks for reading.

Dijkgraaf

11:50 pm on Oct 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As this site has code that achieves that, look at how they do it. In particular the function insert_text