Wrap bb code around selected text in editable div content

So, I'm trying to create an RTE environment. I have editable content div, and I would like to allow the user to select the text, and then click on the button that wraps the BBCode around it.

I tried to create the following function. However, the selected text is simply replaced. It does not seem to store the correct ein selectedText value

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 valid, but I would prefer plain Javascript.

+4
source share
3 answers

Change selectedText = range; on selectedText = range.toString(); . A range is an object, and when you do deleteContents, it destroys the data and therefore is not cleared.

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 + ']'; } } 
+5
source

You need

 var selectedText = range.toString(); 

but not

 var selectedText = range; 

... because the range will not contain text after calling the deleteContents() method.

One more note: console.log(text); will be part of the IE branch if you run it in the IE version without a console or with the console disabled.

+1
source

Another answer that was here works, but only if there are no images in the selection. I simplified it and did work with images in the choice:

https://jsfiddle.net/skeets23/go1nxf06/

 function wrap(tag) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0); range.insertNode(document.createTextNode("["+tag+"]")); range.collapse(); range.insertNode(document.createTextNode("[/"+tag+"]")); } } 

Since I am working on an internal project, I did not become compatible with all browsers, as in another answer, but it works in current versions of firefox and chrome. Doesn't work in IE.

0
source

Source: https://habr.com/ru/post/1397856/


All Articles