javascript - If text is selected, and dropdown option is clicked, change color of selected text -
i want make text editor, , when select text in text area, click option drop down, selected text text area changes color. unfortunately don't know how because when try access drop down, selection text area disappears.
jsfiddle :: http://jsfiddle.net/matthewkosloski/a77sm/
function getselectedtext () { if (window.getselection) { // browsers, except ie before version 9 var range = window.getselection (); var selection = range.tostring(); alert(selection); } }
i've been playing around trying change color of highlighted content within textarea, seems cannot change color of text within textarea. alternative, has been suggested before, create editable div acts rich textbox. can set contenteditable property on div true in order work. here jsfiddle if want play around it.
and here js code. changed couple things on html check out jsfiddle full code.
function getselectedtext (origtext, seltext, tcolor) { //alert(origtext + ", " + seltext + ", " + tcolor); var divcontent = document.getelementbyid('sec'); var spantag = document.createelement("span"); var selindex = origtext.indexof(seltext); var sellength = seltext.length; //split text insert span new color var fpart = origtext.substr(0, selindex); var spart = origtext.substr(selindex + sellength); //alert(fpart + ", " + spart); // add text highlighted , set color spantag.appendchild(document.createtextnode(seltext)); spantag.style.color = tcolor; //remove children of div while(divcontent.haschildnodes()){ divcontent.removechild(divcontent.lastchild); } //append original text highlighted part divcontent.appendchild(document.createtextnode(fpart)); divcontent.appendchild(spantag); divcontent.appendchild(document.createtextnode(spart)); } // function found @ http://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript function gettextfieldselection() { var textcomponent = document.getelementbyid('content'); var selectelem = document.getelementbyid("myselect"); var selectedtext; // ie version if (document.selection != undefined) { textcomponent.focus(); var sel = document.selection.createrange(); selectedtext = sel.text; } // mozilla version else if (textcomponent.selectionstart != undefined) { var startpos = textcomponent.selectionstart; var endpos = textcomponent.selectionend; selectedtext = textcomponent.value.substring(startpos, endpos) } //alert("you selected: " + selectedtext); selectelem.onchange = getselectedtext(textcomponent.value, selectedtext,selectelem.options[selectelem.selectedindex].text.tolowercase()); } var content = document.getelementbyid("content"); var selectelem = document.getelementbyid("myselect"); selectelem.onfocus = function (e) { gettextfieldselection(); };
Comments
Post a Comment