endy endy - 5 months ago 32
Javascript Question

Wrap bb code around selected text in a content editable DIV

So I am trying to create an RTE environment.
I have a content editable div and I would like to allow the user to select text and then press a button which would wrap BBCode around it.

I have tried creating the following function, However, the selected text is just replaced.
It doesn't seem to be storing the proper valu ein selectedText

function wrap(tag)
{


var sel, range;
if (window.getSelection)
{
sel = window.getSelection();
if (sel.rangeCount)
{
range = sel.getRangeAt(0);
var selectedText = range;
range.deleteContents();
range.insertNode(document.createTextNode('['+tag+']'+selectedText+'[/'+tag+']'));
}
}
else if (document.selection && document.selection.createRange)
{
range = document.selection.createRange();
selectedText = document.selection.createRange().text;
console.log(text);
range.text = '['+tag+']'+text+'[/'+tag+']';
}
}


</script>


JQuery is acceptable but I'd prefer regular Javascript.

Answer

Change selectedText = range; to selectedText = range.toString();. The range is an object and when you do deleteContents it wipes out the data and so it doesn't wrape.

DEMO

JS:

function wrap(tag) {
    var sel, range;
    var selectedText;
    if (window.getSelection) {
        sel = window.getSelection();

        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            selectedText = range.toString();
            range.deleteContents();
            range.insertNode(document.createTextNode('[' + tag + ']' + selectedText + '[/' + tag + ']'));
        }
    }
    else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        selectedText = document.selection.createRange().text + "";
        range.text = '[' + tag + ']' + selectedText + '[/' + tag + ']';
    }

}
Comments