var insertsList = [ ["(", ")"], ["{", "}"], ["[", "]"], ["<", ">"] ]; document.onkeypress = function (event) { var node = event.target; if (node.tagName === "TEXTAREA") handleKeyPress.call(node, event); }; /*assumes node to be textarea*/ function handleKeyPress(event) { var keyCode = event.keyCode; // step 1 var charTyped = String.fromCharCode(keyCode), // step 2 index = searchInsertsList(charTyped); // step 3 if (index !== -1) { // step 4 starts event.preventDefault(); // create text var textArray = insertsList[index], text = textArray[0] + textArray[1], val = this.value; var nSS = this.selectionStart, nSE = this.selectionEnd, curPos = nSS + 1; // in the middle of the two characters console.log(text); console.log(val.substring(0, nSS)); console.log(val.substring(nSE)); // set the value this.value = val.substring(0, nSS) + text + val.substring(nSE); this.selectionStart = this.selectionEnd = curPos; } } function searchInsertsList(charTyped) { for (var i = 0, len = insertsList.length; i < len; i++) { // character found? return index if (insertsList[i][0] === charTyped) return i; } return -1; // character not found }
Type a (, {, [, or < <br><br> <textarea></textarea>