9月 06, 2019 Javascript
Sometime you may want to insert a `tab` character (for indent) in a `textarea` element. By default when user hit the `tab` key the current focus element will move to the next element. 

### Add a \t into your current position

By insert a `\t` character right after the current cursor position

```js
// target element
$('#my-textarea').on('keydown', function(evt) {
	
	// get the key code
	var keyCode = evt.keyCode || evt.which;
	
	// tab key
	if (keyCode == 9) {
		
		// prevent default action of key down
		evt.preventDefault();

		// get the textarea DOMElement
		var textarea = this;

		// get the value of textarea
		var value = $(textarea).val();

		// get the cursor current position
		var start = textarea.selectionStart;

		// get the cursor selection end position (if there some text selected)
		var end = textarea.selectionEnd;

		// string before start position
		var start_string = value.substring(0, start);

		// string after end position
		var end_string = value.substring(end, value.length);

		// insert string
		var insert_string = '\t';

		// insert the insert string between string string and end string
		var new_value = start_string + insert_string + end_string;

		// set a new value to textarea
		$(textarea).val(new_value);

		// set the cursor position right after the string just inserted
		textarea.setSelectionRange(start + insert_string.length, start + insert_string.length);
	}
});
```
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)