JavaScript – Enable Tabs In Textareas

Almost every web application that I have seen or used does not allow the user to use the TAB button in textareas to actually insert tabs. encino dentist . Instead it just moves the focus to the next element of the document. True, that is the intended way the browser uses tabs but today’s applications should be a little more user friendly.When I am typing an article in a text editor I want to use tabs. florida auto accident lawyer . When I am using the control panel of my hosting company to edit some code I for sure want to be able to use tabs.So, to solve this problem I came up with the code below to enable that functionality. firefox download . All you have to do is attach the keypressed function to the onkeydown event of the textarea.e.g. document.getElementById(“textareaID”).onkeydown = keypressed;Enjoy!

function keypressed(e){//get key pressedvar key = null;if(window.event) key = event.keyCode;else if(e.which) key = e.which;//if tab pressedif(key != null && key == 9){//IEif(document.selection){//get focusthis.focus();//get selectionvar sel = document.selection.createRange();//insert tabsel.text = "t";}//Mozilla + Netscapeelse if(this.selectionStart || this.selectionStart == "0"){//save scrollbar positionsvar scrollY = this.scrollTop;var scrollX = this.scrollLeft;//get current selectionvar start = this.selectionStart;var end = this.selectionEnd;//insert tabthis.value = this.value.substring(0,start) + "t" + this.value.substring(end,this.value.length);//move cursor back to insert pointthis.focus();this.selectionStart = start+1;this.selectionEnd = start+1;//reset scrollbar positionthis.scrollTop = scrollY;this.scrollLeft = scrollX;}//time for a new browser!!!else this.value += "t";//stop the real tab pressreturn false;}}

comments on this post

Jan 4, 2012 - 09:01:20

You’ve provided me with very definitive information that I needed, but somehow is glossed over or purposely neglected. Your attention to this is greatly appreciated.