javascript - Add "highlight" button to ContentEditable -


i'm making little wysiwyg project, , need ability highlight text, click button, , append span around selection class of ".highlight". span have yellow background.

this have far elsewhere on appending text instead of html. http://jsfiddle.net/agzvp/

here's js:

function wrap(tag) {     var sel, range;      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 + ']';     }  } 

one option class highlighter module of rangy library. has advantage of working in major browsers (including ie 6-8) , working in general case, such when selection includes text starts , ends in different elements.

if case need deal text inside single text node, can create range selection , call surroundcontents() method. see following answer details:

https://stackoverflow.com/a/6328906/96100


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -