Skip to content

Instantly share code, notes, and snippets.

@RomkeVdMeulen
Last active July 30, 2016 18:14
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save RomkeVdMeulen/b59ca36629559a4951256e4b59672580 to your computer and use it in GitHub Desktop.
Vanilla JS code to have textareas wrap text that exceeds the `col` value. Unlike browser wrapping it inserts newlines that are preserved when you copy that textarea contents. Tries to wrap on words if possible.
Array.prototype.forEach.call(document.querySelectorAll("textarea.autowrap"), function(textarea) {
function wrap() {
var cursorPos = textarea.selectionStart;
var newValue = textarea.value.split("\n").map(function(line) {
var wrapped = "";
while (line.length > textarea.cols) {
var wrapPos = line.lastIndexOf(" ", textarea.cols);
if (wrapPos === -1) {
wrapPos = textarea.cols;
}
var wrap = line.substr(0, wrapPos);
wrapped += wrap + (wrap.length > 0 ? "\n" : "");
line = line.substr(wrapPos);
if (line[0] === " ") {
line = line.substr(1);
}
if (line === "\n") {
line = "";
}
}
return wrapped + line;
}).join("\n");
if (newValue.length > textarea.value.length && cursorPos % textarea.cols === 0) {
cursorPos++;
}
textarea.value = newValue;
textarea.selectionStart = textarea.selectionEnd = cursorPos;
}
textarea.addEventListener("input", wrap);
textarea.addEventListener("change", wrap);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment