Forums: Front End:

 

JavaScript textarea selection with mozilla

first
 

StinkFist JavaScript textarea selection with mozilla

Ok, I'm sure you've seen the boards that allow you to select a bit of text and then wrap it in bbcode by pressing a button.

(ours doesn't work that way smile).

Well it's trivial to do it in IE but trying to make it moz compatable is a fucking pain. I finally figured out how to do this by searching the moz bugzilla list and incorporating some of the code used as an example in one of the bug fixes

Here's the library to manipulate text selections:


//--------------------------------------------
// MOZILLA TEXT SELECTION LIBRARY
//--------------------------------------------
function moz_getSelectionStart(element) {
var startpos = 0;
startpos = element.selectionStart;
return startpos;
}

function moz_getSelectionEnd(element) {
var endpos = 0;
endpos = element.selectionEnd;
return endpos;

}

function moz_setSelectionStart(element,newposition) {
element.selectionStart = newposition;
}


function moz_setSelectionEnd(element,newposition) {
element.selectionEnd = newposition;
}

function moz_setSelection(element,newstart,newend) {
setSelectionStart(element,newstart);
setSelectionEnd(element,newend);
}

// Inserts a string at a given position
function moz_stringInsert(DOMEle,newtext,newpos) {
DOMEle.value = DOMEle.value.slice(0,newpos) + newtext + DOMEle.value.slice(newpos);
}



and here's the code for actually inserting the tag:


function moz_markSelected(element,tag) {
var startTag = "[" + tag + "]";
var endTag = "[/" + tag + "]";
var firstPos = moz_getSelectionStart(element);
// we're inserting one at a time
var secondPos = moz_getSelectionEnd(element)+ startTag.length;
moz_stringInsert(element,startTag,firstPos);
moz_stringInsert(element,endTag,secondPos);

// reset focus... after the first tag and before the second
moz_setSelectionStart(element,firstPos + startTag.length);
moz_setSelectionEnd(element,secondPos);
element.focus();
}


obviously this only works for simple wrapper tags but it could be expanded for font-size, etc... tags as well.

Just thought I'd share since it drove me fucking crazy for a while smile

 

arigato

All I know is that it doesn't seem to work in Safari.
big grin

 

StinkFist

:shakesfist:

big grin

I'll post an update when I get it to work wink

 

StinkFist

I still haven't worked on a Safari version but here's an example of the above code

http://droppingbombsonyourmom.com/misc/selection_demo/

 

mosquito

i'm so stealing all of this code. all of it i say!!!!!!

big grin

The significant problems we face cannot be solved by the same level of thinking that created them. - Albert Einstein
quote
 

C.J.

Originally posted by StinkFist
http://droppingbombsonyourmom.com/misc/selection_demo/


I huge improvement over how vBulletin does it. ThumbsUp

 
first
 

Forums: Front End: JavaScript textarea selection with mozilla

 
New Post
 
You must be logged in to post