Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML text area tab support

I am making a web based code editor and am using a textarea for text editing. I want to add tab support to the textarea so that pressing tab doesn't de-focus the element. I have the textarea defined like this:

<textarea id="codeEdit_txt" rows="50" cols="80" onkeydown="return codeEdit_keyDown(event);">

and the function codeEdit_keyDown defined as:

function codeEdit_keyDown(e) {
    if (e.keyCode == 9) {
        return false;
    }
}

This prevents the tab key press from de-focusing the textarea, though it doesn't leave the tab character behind. While I was trying to get this to work initially, I noticed that if I defined the function as below, it would put a tab character at the cursor position.

function codeEdit_keyDown(e) {
    if (e.keyCode == 9) {
        alert("");
        return false;
    }
}

My two questions are:

  1. Why does adding the alert cause a tab to be added?
  2. Is there a way to add the tab at the cursor without having to find the cursor position, split the text in the texarea and manually add a tab character (and without having to have an alert every time the user pressed tab)?

Thanks

EDIT: This only seems to work in Chrome, not in IE, Safari or Firefox

like image 861
Andy Metcalfe Avatar asked May 04 '12 21:05

Andy Metcalfe


People also ask

How do I get tabs to work in textarea?

If the keyCode is 9 (which is the key code for the tab key), we preventDefault() — this means preventing the browser's default behavior, which is usually leaving the textarea to go to the next element. Now, we use setRangeText() , which allows us to manipulate text in the textarea.

What is the HTML for making text area?

The <textarea> element is often used in a form, to collect user inputs like comments or reviews. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier). The size of a text area is specified by the cols and rows attributes (or with CSS).

Is there an HTML tag for tab?

Unlike with HTML space, there is no particular HTML tab character you could use. You could technically use the &#9; entity as the tab is character 9 in the ASCII. Unfortunately, HTML parsers will simply collapse it into a single space due to the whitespace collapse principle. There used to be a special tab element.

What is the tab character in HTML?

In HTML the horizontal tab is coded using &#9; or &Tab; but as with all whitespace characters in HTML, this will be displayed as a single space except inside <pre> , <code> tags (or other elements with CSS attribute white-space set to pre ).


2 Answers

See this question:

https://stackoverflow.com/a/13130/420001

You're looking for .preventDefault();

EDIT: A fiddle.

EDIT 2: A better fiddle, thanks to rainecc.

like image 50
Josh Avatar answered Sep 20 '22 15:09

Josh


The other answer is nice, but it ends tabs at the end. I looked up how to add the tab at the cursor location, and added that to the solution.

You can find the working code here: http://jsfiddle.net/felixc/o2ptfd5z/9/

Code inline as a safeguard:

		function insertAtCursor(myField, myValue) {
			//IE support
			if (document.selection) {
				myField.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
			}
			//MOZILLA and others
			else if (myField.selectionStart || myField.selectionStart == '0') {
				var startPos = myField.selectionStart;
				var endPos = myField.selectionEnd;
				myField.value = myField.value.substring(0, startPos)
					+ myValue
					+ myField.value.substring(endPos, myField.value.length);
				myField.selectionStart = startPos + myValue.length;
				myField.selectionEnd = startPos + myValue.length;
			} else {
				myField.value += myValue;
			}
		}	

		function addTabSupport(elementID, tabString) {
			// Get textarea element
			var myInput = document.getElementById(elementID);

			// At keydown: Add tab character at cursor location
			function keyHandler(e) {
				var TABKEY = 9;
				if(e.keyCode == TABKEY) {
					insertAtCursor(myInput, tabString);
					if(e.preventDefault) {
						e.preventDefault();
					}
					return false;
				}
			}			

			// Add keydown listener
			if(myInput.addEventListener ) {
				myInput.addEventListener('keydown',keyHandler,false);
			} else if(myInput.attachEvent ) {
				myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
			}
		}
    
    // easily add tab support to any textarea you like
    addTabSupport("input", "\t");
<h1>Click in the text and hit tab</h1>

<textarea id="input" rows=10 cols=50>function custom(data){
	return data;
}</textarea>
like image 22
felixc Avatar answered Sep 17 '22 15:09

felixc