Last active
July 30, 2016 18:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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