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.
Change
selectedText = range;toselectedText = 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: