Reputation: 297
I'm trying to simulate tabbing in a textarea, so far tab forward works but I'm not quite sure how to make backtab work. Any suggestions on how to do this, or better ways to do it would be helpful.
$('textarea').on('keydown mousedown', function(e){
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.shiftKey) {
console.log('shift')
if (e.which == 9 || e.keyCode == 9) {
console.log('shift + tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
} else if (e.which == 9 || e.keyCode == 9) {
console.log('tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
})
Upvotes: 4
Views: 934
Reputation: 702
This might get you started.
$('textarea').on('keydown mousedown', function(e) {
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
if (e.shiftKey) {
var firstTabPoint = val.lastIndexOf('\n', start) + 1;
if (val.substring(firstTabPoint, firstTabPoint + 1) == '\t') {
var startString = val.substr(0, firstTabPoint);
var endString = val.substr(firstTabPoint + 1);
this.value = startString + endString;
this.setSelectionRange(start - 1, end - 1);
}
} else {
this.value = val.substring(0, start) + '\t' + val.substring(end);
this.setSelectionRange(start + 1, end + 1);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" cols="100">
Add some lines in here, tab them, and then try untabbing.
</textarea>
As a side note, you might look into the attribute contenteditable="true"
if you are making a text editor application.
Upvotes: 3