i developing wysiwyg editor , unable undo effect applied earlier.
example: if select text , bold it, works fine. if want remove bold effect on it, unable classname applied selected text. (line # 6 in js) in console, can see exists under sel > anchornode > nextelementsibling > classname
not sure why not allowing fetch that.
function replaceselectedtext(classname) { var selectedtext, sel, range; if (window.getselection) { sel = window.getselection(); // check if selection has class if(sel.anchornode){ console.dir(sel); if(sel.anchornode.nextelementsibling){ console.log("classname:" + sel.anchornode.nextelementsibling.classname); } } selectedtext = window.getselection().tostring(); //console.log(selectedtext); if (sel.rangecount) { range = sel.getrangeat(0); range.deletecontents(); var element = document.createelement('span'); element.classname = classname; element.textcontent = selectedtext; range.insertnode(element); } } else if (document.selection && document.selection.createrange) { range = document.selection.createrange(); range.text = replacementtext; } } var toolbarbuttons = document.queryselectorall("#toolbar button"); //console.log(toolbarbuttons); (var = 0; < toolbarbuttons.length; ++i) { toolbarbuttons[i].addeventlistener('click', function(){ replaceselectedtext(this.id); console.log(document.getelementbyid("editable").innerhtml); }); }
#editable{ border: 1px solid #000000; margin-top: 20px; height: 50px; font-family: arial; } .bold{ font-weight: bold; } .italic{ font-style: italic; }
<div id="toolbar"> <button id="bold">bold</button> <button id="italic">italic</button> </div> <div id="editable" contenteditable="true"> <div>lorem ipsum lorem ipsum</div> </div>
it works in firefox not in chrome.
how classname in chrome?
there seems individual solutions chrome , firefox.
firefox: sel.anchornode.nextelementsibling.classname
chrome: sel.basenode.parentelement.classname
i fixed detecting browser.
detecting browser:
var isopera = !!window.opera || navigator.useragent.indexof(' opr/') >= 0; // opera 8.0+ (ua detection detect blink/v8-powered opera) var isfirefox = typeof installtrigger !== 'undefined'; // firefox 1.0+ var issafari = object.prototype.tostring.call(window.htmlelement).indexof('constructor') > 0; // @ least safari 3+: "[object htmlelementconstructor]" var ischrome = !!window.chrome && !isopera; // chrome 1+ var isie = /*@cc_on!@*/false || !!document.documentmode; // @ least ie6
js conditions:
if(ischrome){ if(sel.basenode.parentelement.classname){ console.log("ischrome classname:" + sel.basenode.parentelement.classname); sel.basenode.parentelement.classname = ""; return false; } } if(isfirefox){ if(sel.anchornode.nextelementsibling){ console.log("isfirefox classname:" + sel.anchornode.nextelementsibling.classname); sel.anchornode.nextelementsibling.classname = ""; return false; } }
Comments
Post a Comment