javascript - Superscripts and subscripts in HTML input -
i making small javascript web app deals chemical formulas, need allow users input superscripts. easiest thing users having text editor switch superscript when press ^. how can html textarea?
borrowing function in adeneo's answer
check fiddle here : fiddle
usage : type superscript , press ^ --> type in superscript --> press esc , superscript appear in textarea.
$(document).ready(function() { var temp = {}; // store keypresses here var current_value = ""; $("#text_area").keydown(function(e) { temp[e.which] = true; }); $('#text_area').keyup(function(e) { if (e.keycode == 27 && current_value != "") { var length_1 = current_value.length; var length_without_sup = length_1 - 5; var substr_superstring = $('#text_area').val().substr(length_without_sup); var current_text_2 = current_value + substr_superstring; current_text_2 = current_text_2 + "</sup>"; $('#text_area').val(current_text_2); $('#text_area').superscript(); } var flag_shift = false; var flag_super = false; (var key in temp) { if (key == 16) { flag_shift = true; } else if (key == 54) { flag_super = true; } } if (flag_shift == true && flag_super == true) { var current_text = $('#text_area').val(); current_text_2 = current_text.substr(0, current_text.length - 1); current_text_2 = current_text_2 + "<sup>"; $('#text_area').val(current_text_2); current_value = hide_superscript_tag(); } delete temp[e.which]; }); }); function hide_superscript_tag() { var current_value = $('#text_area').val(); current_value_2 = current_value.substr(0, current_value.length - 5); $('#text_area').val(current_value_2); return current_value; } $.fn.superscript = function() { var chars = '+−=()0123456789aaÆᴂɐɑɒbbcɕddðeeƎəɛɜɜfggɡɣhhɦiiɪɨᵻɩjjʝɟkkllʟᶅɭmmɱnnɴɲɳŋooɔᴖᴗɵȢppɸqrrɹɻʁsʂʃttƫuuᴜᴝʉɥɯɰʊvvʋʌwwxyzʐʑʒꝯᴥβγδθφχнნʕⵡ', sup = '⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ᴬᵃᴭᵆᵄᵅᶛᴮᵇᶜᶝᴰᵈᶞᴱᵉᴲᵊᵋᶟᵌᶠᴳᵍᶢˠʰᴴʱᴵⁱᶦᶤᶧᶥʲᴶᶨᶡᴷᵏˡᴸᶫᶪᶩᴹᵐᶬᴺⁿᶰᶮᶯᵑᴼᵒᵓᵔᵕᶱᴽᴾᵖᶲqʳᴿʴʵʶˢᶳᶴᵀᵗᶵᵁᵘᶸᵙᶶᶣᵚᶭᶷᵛⱽᶹᶺʷᵂˣʸᶻᶼᶽᶾꝰᵜᵝᵞᵟᶿᵠᵡᵸჼˤⵯ'; return this.each(function() { this.value = this.value.replace(/<sup[^>]*>(.*?)<\/sup>/g, function(x) { var str = '', txt = $.trim($(x).unwrap().text()); (var = 0; < txt.length; i++) { var n = chars.indexof(txt[i]); str += (n != -1 ? sup[n] : txt[i]); } return str; }); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="text_area"> </textarea>
Comments
Post a Comment