PDA

View Full Version : Focusing the Cursor



radostsguy
06-05-2008, 09:56 AM
I have used "Anylink" to create a Smilies table for my Site's Blogs. It's fine, so this is NOT a Dynamicdrive query! The problem is that I have used this:

function doCopyS(smilie) {
myvalue=document.myform.mytext.value;
value=myvalue+' '+smilie;
document.myform.mytext.value=value;
myform.mytext.focus();}

"myform" and "mytext" refer to the textarea in which the user types the text for the blog.

It almost works. The only thing is that it places the curor in front of the smilie coding (as in :lol:) instead of after it where I want it. Any ideas? If you want more info, I can zip the whole thing up, stick it into one of my many Downloaders, and then post the URL here.

If you want to see it in action, go here (test site):

http://mwob-test.dynalias.com/Smilies-table.html

jscheuer1
06-06-2008, 01:57 AM
First off, your function can be simplified:


function doCopyS(smilie) {
document.myform.mytext.value += ' '+smilie;
document.myform.mytext.focus();
}

After getting that, I found this using Google (search terms - move cursor textarea javascript):


function setCursorPosition(oInput,oStart,oEnd) {
if( oInput.setSelectionRange ) {
oInput.setSelectionRange(oStart,oEnd);
}
else if( oInput.createTextRange ) {
var range = oInput.createTextRange();
range.collapse(true);
range.moveEnd('character',oEnd);
range.moveStart('character',oStart);
range.select();
}
}

at this address:

http://www.faqts.com/knowledge_base/view.phtml/aid/15728

Put it all together:


function setCursorPosition(oInput,oStart,oEnd) {
if( oInput.setSelectionRange ) {
oInput.setSelectionRange(oStart,oEnd);
}
else if( oInput.createTextRange ) {
var range = oInput.createTextRange();
range.collapse(true);
range.moveEnd('character',oEnd);
range.moveStart('character',oStart);
range.select();
}
}

function doCopyS(smilie) {
document.myform.mytext.value += ' '+smilie;
document.myform.mytext.focus();
setCursorPosition(document.myform.mytext, document.myform.mytext.value.length, document.myform.mytext.value.length);
}

Works here.