Reputation: 195
I want to enable 4-width indentation with tabs on <textarea>
. Currently, the "\t"
adds an 8-width indent. How can I change that to 4? Switching the "\t"
for 4 spaces doesn't work, results in a single whitespace being added, instead of the 4 I want.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
$('#input').on('keydown', function(e) {
if (e.keyCode == 9 || e.which == 9) {
e.preventDefault();
var s = this.selectionStart;
$(this).val(function(i, v) {
return v.substring(0, this.selectionStart) + "\t" + v.substring(this.selectionEnd)
});
this.selectionEnd = s + 1;
}
});
});
</script>
</head>
<body>
<textarea id="input" style="font-family:monospace"></textarea>
</body>
</html>
Upvotes: 0
Views: 66
Reputation: 4884
You can try the code below.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
var SPACE = ' '.repeat(4);
var $input = $('#input');
$input.on('keydown', function(e) {
if (e.keyCode === 9 || e.which === 9) {
e.preventDefault();
var start = this.selectionStart;
var txt = $input.val();
txt = txt.substring(0, start) + SPACE + txt.substring(this.selectionEnd);
$input.val(txt);
start += SPACE.length;
this.setSelectionRange(start, start);
}
});
});
</script>
</head>
<body>
<textarea id="input" style="font-family:monospace"></textarea>
</body>
</html>
You should note that:
(1) I've moved the spacing information to a separate variable so that it can be easily changed later (if needed).
(2) The code updates the selection range of the textarea after it changes the contents. In other words, we have to move the caret back to where it was and keep the user experience good.
Upvotes: 1
Reputation: 195
Taplar's answer worked for me:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
$('#input').on('keydown', function(e) {
if (e.keyCode == 9 || e.which == 9) {
e.preventDefault();
var s = this.selectionStart;
$(this).val(function(i, v) {
return v.substring(0, this.selectionStart) + "\t" + v.substring(this.selectionEnd)
});
this.selectionEnd = s + 1;
}
});
});
</script>
</head>
<body>
<textarea id="input" style="font-family:monospace;tab-size:4"></textarea>
</body>
</html>
Upvotes: 0