Ok, so here is a messy, but functional way to do what you are asking. What this does is use a hidden div to measure the width against the original as we add words in one-by-one. Then, once the width threshold is reached, we create a new span
element containing the words collected so far. Wash. Rinse. Repeat. Lastly, we scoop up the remaining words and add them to their own span
, and replace the original text with our new HTML. You can use the wordWrap()
function anytime the document loads or window resizes. I've added some borders to the span elements, just so you can easily see where the markup is being applied.
$(document).ready(function() {
wordWrap();
});
function wordWrap() {
var bdy = $(".body-copy");
var text = $(bdy).text();
var html = $(bdy).html();
var bWidth = $(bdy).width();
var words = text.split(" ");
var span = "";
var word = "";
var allSpans = "";
var lastWord = "";
$(words).each(function(i, w) {
if (lastWord != "") {
w = lastWord + " "+ w ;
lastWord = "";
};
word = w + " ";
span = span + word;
$(".body-copy-two").append(word);
if ($(".body-copy-two").width() >= bWidth) {
var wLen = word.length;
span = span.slice(0, -wLen);
lastWord = w + " ";
allSpans = allSpans + "<span>" + $.trim(span) + "</span>";
$(".body-copy-two").html("");
span = "";
word = "";
}
});
var lastSpan = "<span>" + $(".body-copy-two").text() + "</span>";
$(bdy).html(allSpans + lastSpan);
}
.body-copy {
position: relative;
width: 100%;
height: auto
}
.body-copy-two {
position: absolute;
visibility: hidden;
}
.body-copy span {
border: 1px solid black;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body-copy">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.
</div>
<div class="body-copy-two"></div>