'Catching Tabs in TextArea

Does anyone know a cross-browser, reliable solution for catching presses of the tab-key in a textarea field, and replacing (in the correct position) 4 spaces? The textarea is being used to input an essay, and needs this feature.

Note: I tried using FCKEditor, among others, which did not catch tabs and had a bunch of features I didn't need. I want a simple solution just for catching tabs.



Solution 1:[1]

<html>
<head>
    <script type="text/javascript">

        function keyHandler(e) {
            var TABKEY = 9;
            var backSlash = 8;
            var code = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
            if(code == TABKEY && !e.shiftKey && !e.ctrlKey && !e.altKey) {
            var val = document.getElementById("t1");
                val.value=(val.value).substring(0,getCaret(val)) + "    " + (val.value).substring(getCaret(val));
                //document.getElementById("t1").value += "    ";

                if(e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
                val.focus(); 
                return false;
            }
            if(code == backSlash) {
                var val = document.getElementById("t1");
                val.value=(val.value).substring(0,getCaret(val)-4) + (val.value).substring(getCaret(val));
                if(e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
                return false;
            }

        }

        function getCaret(el) { 
          if (el.selectionStart) { 
            return el.selectionStart; 
          } else if (document.selection) { 
            el.focus(); 

            var r = document.selection.createRange(); 
            if (r == null) { 
              return 0; 
            } 

            var re = el.createTextRange(), 
                rc = re.duplicate(); 
            re.moveToBookmark(r.getBookmark()); 
            rc.setEndPoint('EndToStart', re); 

            return rc.text.length; 
          }  
          return 0; 
        }
    </script>
</head>
<body>
 <textarea id="t1" onkeydown="javascript:keyHandler(event)"></textarea>

</body>
</hrml>

Solution 2:[2]

Is there some reason you can't just replace the tabs after the editing is done? I've played around quite a bit with replacing text while typing in a textarea, and found it to be... impractical at best.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RAMCHANDAR THOPUCHARLA
Solution 2 Dave