Allow Tab Key in Textareas Using JavaScript

- 1 minute read

This JavaScript snippet will grab all the <textarea> elements in the DOM and override the default tab key functionality:

document.querySelectorAll(`textarea`).forEach((textArea) => {
    textArea.addEventListener(`keydown`, (e) => {
        if (e.keyCode === 9) {
            textArea.value = `${textArea.value.substring(0, textArea.selectionStart)}\t${value.substring(textArea.selectionEnd)}`;
            textArea.selectionEnd = textArea.selectionStart + 1;
            textArea.selectionStart = textArea.selectionEnd;
    }, false);

After the above code has run, pressing the tab key when focused within a textarea will override the default behavior of losing focus and instead insert a tab stop.

Link to this section Conclusion

You don’t have to insert a tab stop each time the tab key is pressed - you could also enter two or four spaces instead, and so on.

In any case, I hope you found this useful!