I am currently having a problem with my BB-code editor, like most things it works great in FF, but i have an issue with IE: whenever i select a word that has already been previously typed, it selects that word instead of the one i selected.

Here is the selection part of my editor:

if (window.getSelection){ 
selection = window.getSelection(); 
}else if (document.getSelection){ 
selection = document.getSelection(); 
}else if (document.selection){ 
selection = document.selection.createRange().text; 
}

Example:

The text: the cats attack the other cats
I selected the second "cats", but the script keeps returning the first "cats"

Does anyone have a suggestion on how to fix this?

Recommended Answers

All 9 Replies

Oops, the code was incomplete, here is full encoding for IE:

if (window.getSelection){ 
selection = window.getSelection(); 
}else if (document.getSelection){ 
selection = document.getSelection(); 
}else if (document.selection){ 
selection = document.selection.createRange().text; 
} 
var startPos = myArea.value.indexOf(selection); 
if (startPos >= 0){ 
var endPos = myArea.value.indexOf(selection) + selection.length; 
begin = myArea.value.substr(0,startPos); 
end = myArea.value.substr(endPos, myArea.value.length); 
textselected = true; 
}

Graphix,

On first look, I would guess that the code you posted above is OK in that it is correctly identifying the content of the highlighted string.

The problem would appear to be in some other block of code, where it handles BBcode insertion (or whatever). I guess there's a regular expression which attempts to re-identify the selected string within the overall text, and then handles it according to what the user requested.

That said, I can't immediately see why IE should behave differently from FF. Could you identify the block of code and post it?

Airshow

Ok, i thought that part of the code was the only needed, but here is it all :) :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>
<body>
<script type="text/javascript"> 
function addBB(t){ 
//crappy browser sniffer 
var isFF = false; 
var textselected = false; 
if(navigator.userAgent.toLowerCase().indexOf("firefox") > 0){ 
isFF = true; 
} 
var myArea = document.getElementById("text"); 
var begin,selection,end; 
if (isFF == true){ 
if (myArea.selectionStart!= undefined) {  
begin = myArea.value.substr(0, myArea.selectionStart);  
selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);  
end = myArea.value.substr(myArea.selectionEnd); 
if (selection.length > 0){ 
textselected = true; 
} 
} 
}else{ 
if (window.getSelection){ 
selection = window.getSelection(); 
}else if (document.getSelection){ 
selection = document.getSelection(); 
}else if (document.selection){ 
selection = document.selection.createRange().text; 
} 
var startPos = myArea.value.indexOf(selection); 
if (startPos >= 0 && t != "image"){ 
var endPos = myArea.value.indexOf(selection) + selection.length; 
begin = myArea.value.substr(0,startPos); 
end = myArea.value.substr(endPos, myArea.value.length); 
textselected = true; 
} 
} 
if(textselected == true){ 
switch (t){ 
case "color": 
var color = window.prompt("Enter the color in english below:");
if (color != "" && color != "undefined" && color != "null" && color != 0 && color != null) {
startTag = "[color=" + color + " ]"; 
endTag = "[/color ]\n"; 
}
break; 

case "bold":
startTag = "[b ]";
endTag = "[/b ]";
break;

case "italics":
startTag = "[i ]";
endTag = "[/i ]";
break;

case "underline":
startTag = "[u ]";
endTag = "[/u ]";
break;

case "link":
var link = window.prompt("Enter the link below:");
if (link != "" && link != "undefined" && link != "null" && link != 0 && link != null) {
startTag = "[link=" + link + " ]";
endTag = "[/link ]";
}
break;

case "size":
var size = window.prompt("Enter the text-size below:");
if (size != "" && size != "undefined" && size != "null" && size != 0 && size != null) {
startTag = "[size=" + size + "px ]";
endTag = "[/size ]";
break;
}

}
myArea.value = begin + startTag + selection + endTag + end;
myArea.focus();
}else{
if (t == "image") {
var image = prompt("Enter the filename or url to the image below:");
if (image != "" && image != "undefined" && image != "null" && image != 0 && image != null) {
startTag = "[img ]";
endTag = "[/img ]";
if (isFF == true) {
myArea.value = begin + startTag + image + endTag + end;
} else {
var addTxt = startTag + image + endTag;
myArea.value += addTxt;
}
myArea.focus();
}
} else {
alert("There is not text selected.");
myArea.focus();
}
}
startTag = "";
endTag = "";
end = "";
begin = "";
} 
</script>
<div class="warning"></div><h2>Adjusting page: example</h2>
<form action="edit.php?pagename=example" method="post" name="editform">
You can adjust the text below (menu only works if scriptswindows and JavaScript are enabled):<br /><br />
<img src="beheerimages/ibutton.jpg" onClick="addBB('italics')" />
<img src="beheerimages/ubutton.jpg" onClick="addBB('underline')" />
<img src="beheerimages/bbutton.jpg" onClick="addBB('bold')" />
<img src="beheerimages/colorbutton.jpg" onClick="addBB('color')" />
<img src="beheerimages/sizebutton.jpg" onClick="addBB('size')" />
<img src="beheerimages/linkbutton.jpg" onClick="addBB('link')" />
<img src="beheerimages/imagebutton.jpg" onClick="addBB('image')" />
<br />
<textarea class="editarea" name="text" id="text" cols="120" rows="23">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi magna eros, consectetur sed dictum vel, sodales ut nulla. Praesent sapien ante, consequat a vestibulum a, mattis sit amet mauris. Fusce vel purus nunc. Donec posuere fermentum tellus quis mattis. Cras turpis tellus, congue aliquet condimentum in, tincidunt in orci. In lacinia tempus quam in feugiat. Nulla pulvinar malesuada arcu, sit amet aliquet ante pulvinar eu. Donec blandit dignissim adipiscing. Proin ipsum felis, tincidunt eget posuere porta, eleifend et eros. Donec et quam est. Curabitur scelerisque neque pellentesque diam hendrerit pellentesque dictum quam pulvinar. Duis vitae arcu lorem. Duis vitae mollis nunc. Aenean in eros quis eros lobortis bibendum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce eget lorem justo. 

Suspendisse diam magna, viverra condimentum ullamcorper vel, vestibulum at velit. Nunc arcu augue, gravida at pharetra vitae, bibendum et sem. Donec fermentum velit molestie arcu gravida vitae blandit dui egestas. Proin at mattis mi. Morbi urna sem, fringilla vel auctor eget, tempor vitae dui. Integer diam justo, ultrices vitae lobortis et, tincidunt vitae ipsum. In accumsan nisi in nibh luctus non gravida nisl ultricies. Integer egestas, nunc eget commodo imperdiet, mauris diam convallis leo, tincidunt faucibus odio mi in sapien. Etiam commodo dolor eu elit venenatis feugiat. Nam rutrum ante vel lacus adipiscing scelerisque. 

Nunc imperdiet mollis neque at ullamcorper. Pellentesque sodales metus cursus est bibendum tincidunt porta odio pretium. Nam egestas massa in magna aliquet pretium. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer fermentum elit imperdiet lorem sodales a faucibus enim aliquam. Cras eu nibh ante, eget iaculis sapien. Ut consequat, massa non bibendum lobortis, ligula dui varius elit, id volutpat dui enim vitae sapien. Ut adipiscing interdum purus vitae sodales. Integer ut est sit amet lacus blandit dapibus in nec elit. Nunc molestie orci non tortor scelerisque viverra. In erat nunc, vehicula nec aliquam et, ullamcorper pellentesque nunc. Sed ipsum velit, sagittis eu feugiat et, ullamcorper nec nunc. Vivamus auctor, mi in volutpat rutrum, metus lorem fringilla nibh, quis dignissim odio mauris eu magna. Suspendisse congue mattis tortor, sit amet ullamcorper odio euismod vel. Nam in volutpat metus. Morbi varius lorem quis libero scelerisque sed ornare lectus mattis. Praesent ut augue erat, vitae hendrerit eros. Nullam convallis, purus quis posuere placerat, ipsum nunc fringilla ante, et rhoncus enim urna ac nisi. Mauris interdum interdum lacus rhoncus tincidunt. 

Etiam sed nunc mauris, sed consequat felis. Phasellus posuere, neque sit amet tincidunt aliquam, diam velit ultricies nibh, id pulvinar nunc nibh sed sapien. Pellentesque porttitor, nulla vel aliquet hendrerit, turpis eros viverra odio, non vulputate urna sem eu dui. Suspendisse suscipit dolor nec urna tempor lacinia condimentum lorem ultrices. Ut a hendrerit mauris. Maecenas sit amet congue quam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras ut purus eu elit placerat rhoncus. Duis tristique commodo risus ac porttitor. Pellentesque tempus nulla at justo pellentesque aliquet. Quisque in augue in magna vehicula egestas sed a ante. Duis tempus magna eu augue venenatis aliquet. Donec mattis nulla in mauris interdum tincidunt. Ut ac ipsum et dui viverra elementum. Sed vehicula semper nisl et tempus. Integer rutrum vehicula purus, pulvinar ultricies sapien condimentum eget. 

Nulla eu pretium lectus. Fusce nunc orci, feugiat id tincidunt ut, tempus nec justo. Nullam quis nulla vel mi facilisis lacinia vitae pharetra augue. Maecenas magna tellus, cursus in tristique a, feugiat id mauris. Vestibulum a lorem vel metus ultrices fermentum at non turpis. Nullam porta mollis tempor. Maecenas vehicula, est quis elementum sodales, turpis lectus interdum metus, nec adipiscing neque tellus ac dolor. Nunc at pharetra velit. Vivamus molestie varius aliquam. Ut euismod, nisl vitae convallis laoreet, nibh enim hendrerit diam, in iaculis tortor urna at est. Maecenas iaculis, enim in ornare feugiat, nisl velit ultrices ante, sed consectetur erat purus quis lacus. Cras accumsan mi ac libero elementum eu sodales nulla euismod. Cras bibendum, lorem nec elementum tempor, justo ligula aliquet urna, sit amet aliquet elit magna vitae magna. Donec vel accumsan elit. 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat. Fusce nec tortor massa, molestie molestie metus. Donec sagittis lorem vel massa tempus feugiat. Duis volutpat, tortor quis lacinia tristique, ipsum orci volutpat tortor, non lobortis tortor augue a nunc. Pellentesque ultricies accumsan urna a mollis. Nullam vitae elementum dui. Praesent auctor auctor ante quis ultrices. Nam auctor scelerisque neque eu rutrum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum eget libero quis magna pretium laoreet. Ut porttitor facilisis pulvinar. Vivamus aliquet semper lectus, et rutrum elit adipiscing tempus. Vestibulum eleifend rhoncus dui at condimentum. Quisque tellus libero, tempus sit amet dignissim ut, ultrices eget metus. 
</textarea><br /><br />
<input type="submit" name="savebutton" value="Save changes" />
</form>
</body>
</html>

EDIT 1: I added spaces in the BB-codes to prevent Daniweb from highlighting them.
EDIT 2: Translated Dutch into English

Graphix,

I can see it now. The problem is caused by the line var startPos = myArea.value.indexOf(selection); which will always find the first occurrence of selection regardles of which occurrence was selected by the user.

For versions of IE that support document.selection.createRange() , the solution is simple, because you don't need to know begin and end . You simply do the text substitution with:

document.selection.createRange().text = startTag + selection + endTag;

(with suitable safety to ensure (a) that there is a selection exists and (b) that the selection is within the textarea).

I'm not sure how to handle browsers which support only window.getSelection or document.getSelection . Maybe just accept that automatic insertion of BB tags is not supported in such browsers (eg. IE on the Macintosh).

Airshow

Thank you, that solved the problem :). I also tryed with Google Chrome and Safari, but both can't retrieve the selected text. I guess iil have to live with it that there are only 2 that support BB-code: IE and FF (luckily the 2 most used browsers on the world). Thread solved.

~G

Graphix,

Remember, users can always type the BBCode for themselves. All you need to do is provide a link to some instructional text.

Airshow

Graphix,

Another thought. Chrome, Safari, Opera may work with the FF code block. Try expanding the sniffer to include them.

In fact, instead of browser sniffing, you could try testing with if(selectionStart) . That way, if it's supported, the condition should be met. But you will need to test to see it behaves correctly when no selection exists.

Another approach would be to use a try/catch structure.

Airshow

The if(selectionStart)-statement didn't work as there was no text selected. I extended the sniffer and came up with this easy solution. As i made a separate method of placing the bb-code with getSelection(), I just made sure that the browser wasn't IE (as only IE doesn't support selectionStart and all other browsers are an extension of Netscape Navigator)

if(navigator.appName != "Microsoft Internet Explorer"){ 
isFF = true; 
}

~G

Seems reasonable.

If you want to see fully worked up bbCode scripts then take a look under the hood of open source bulletin boards such as phpBB, vBulletin, yaBB, phpNuke. They each comprise several thousand files so it can sometimes take time to find the code you are looking for. On the plus side, they are generally well orgnised.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.