For some reason, I was never alerted when this post was updated...and last night, I had this BRILLIANT idea on how to determine where the line breaks were...
I would rebuild the string, and check the width each time, and it WORKED
so I came here to share it...and found I was 1 week behind
Anyway 2 important things
The code you provided uses the same brilliant idea I had (well done you) BUT when I test it, it breaks the first line correctly then adds a line break after every character (tested on the link jsfiddle.net)
I've added my code which uses jquery and uses the width of a span to determine when to break
At first I tried using the width of the div, but div.width() returns the default width, not the width of the content.
I AM AWARE THIS MAY NOT WORK ON ALL BROWSERS
so, I ask kindly that if anyone knows of a way of making this foolproof, or close to it, please share.
First, the styles are necessary to synchornize fonts (all attributes) between the textarea and div, set the size, and (for IE) remove any scrollbars that automatically appear.
.inputArea {
width:200px;
height:100px;
font-family:Arial;
font-size:12px;
overflow: auto;
border: 1px solid #cccccc;
padding:0;
margin:0;
}
.divArea {
font-family:Arial;
font-size:12px;
}
Next, I include jquery and my custom functions:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#breakUp").click(function () {
showLineBreaks();
addLineBreaks();
});
function showLineBreaks() {
content = $("#textEntered").val();
//replace line breaks in content with "|" to allow for replacement below
content = content.replace("\r\n", "
");
content = content.replace("\r", "
");
content = content.replace("\n", "
");
$("#unedited").html(content);
}
function addLineBreaks() {
content = $("#textEntered").val();
//replace line breaks in content with "|" to allow for replacement below
content = content.replace("\r\n", "|");
content = content.replace("\r", "|");
content = content.replace("\n", "|");
tempContent = "";
$("#edited").html("");
for (var i = 0; i ");
} else {
tempContent = $("#edited").html();
$("#edited").html(tempContent + content.charAt(i));
if ($("#edited").width() > 200) {
$("#edited").html(tempContent + "
" + content.charAt(i));
}
}
}
}
});
<script>
And finally, my html test page
Enter text into the textarea below (Set to 200 px width, 100 px height)<br>
<textarea id="textEntered" class="inputArea"></textarea>
<br><br>
The div below will display that text WITHOUT wrapping, BUT replacing all existing line breaks with <br><br>
<div id="unedited"></div>
<br>
The following div will display that text with line breaks ADDED to fit the wrapping<br>
<div class="divArea"><span id="edited"></span></div>
<br>
<button id="breakUp">Click Here to Convert</button>