Reputation:
I want to get the first line of the text contents of a div where the text has been wrapped on to several lines by the browser due to div's styling which only shows the first row. Here is the HTML div and the styling used to hide all but the first line:
<div id="element"
style="display: inline-block; height: 20px; overflow: hidden;
width: 70px;">asdfl asf af adf adsf dsaf adsf adsfdsa fdsaf dsa fdas fdsa f dsaf dsa fdsa f dsaf sad</div>
The text within the div is not pre-wrapped, the and tags and the contained text are all on the same line (as shown), there are no embedded new-lines (\n), and the font is not fixed (so counting characters within the string won't work).
When I inspect the div's, the innerHTML and innerText both contain:
"asdfl asf af adf adsf dsaf adsf adsfdsa fdsaf dsa fdas fdsa f dsaf dsa fdsa f dsaf sad"
For this example, I want to only get 'asdfl asf' after any trailing spaces have been trimmed, if there are any.
The heart of the issue is to be able to get the string as the browser wrapped it.
Upvotes: 0
Views: 1436
Reputation: 66650
In order to get first line you need remove all text and in loop adding characters one by one and if text have height bigger then single character, then the previous character was the last one.
function get_first_line(element) {
var original = element.text();
element.text(original[0]);
var height = element.height();
var first = original;
for (var i = 2; i < original.length; ++i) {
element.text(original.slice(0, i));
if (element.height() > height) {
first = original.slice(0, i - 1);
break;
}
}
element.text(original);
return first;
}
EDIT And here is working code with hyphens, the solution is to wrap each character in span, they are inline elements so they work the same as characters in term of wrapping.
function get_first_line(element) {
var original = element.text();
var text = original.trim();
// if you care about IE change it to normal function
element.html(text.split('').map((c) => '<span>' + c + '</span>'));
var chars = element.find('span');
var offset = chars.eq(0).offset();
var first = original;
for (var i = 1; i < chars.length; i++) {
if (chars.eq(i).offset().top > offset.top) {
first = text.slice(0, i);
break;
}
}
element.text(original);
return first;
}
And codepen demo https://codepen.io/jcubic/pen/erBRmb?editors=1010
Upvotes: 1