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: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
To edit the content in HTML, we will use contenteditable attribute. The contenteditable is used to specify whether the element's content is editable by the user or not. This attribute has two values. true: If the value of the contenteditable attribute is set to true then the element is editable.
You can add the contenteditable="true" HTML attribute to the element (a <div> for example) that you want to be editable. If you're anticipating a user to only update a word or two within a paragraph, then you could make a <p> itself editable.
Try something like this: // Disable all input-like elements in the divs except for the last div $(". divclass:not(:last-child) :input"). attr("disabled", true);
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 + ']';
}
}
You need
var selectedText = range.toString();
rather than
var selectedText = range;
... because the range will contain no text after its deleteContents()
method has been called.
One other note: console.log(text);
will throw in the IE branch if you run it in a version of IE without a console or with console disabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With