This turned out to be more complicated than I expected, so I'm curious if there's a better / faster way to do it.
Let's say that I have this:
<p>
<a href="#">csdude@example.com</a>, that's not real, obviously
</p>
This would "usually" fit the area, but when the title is longer than expected with no whitespaces and the viewport is small, it's wrapping weird. In production I have 3 PHP variables in a row so it's not a simple matter of forcing one of them to be smaller; I don't necessarily know that it's going to wrap until it's on the screen.
So my solution is to measure the height of the container, and if it's more than expected then the text wrapped; in that case, I change the .html() of one of the variables to replace the middle with ...; so, I might end up with:
csdud....e.com
But I have to keep measuring it until it is small enough to stop wrapping, so I have it in a loop. I already use jQuery, so I've ended up with this:
<p>
<a href="#" class="shorten">csdude@example.com</a>, that's not real, obviously
<p>
<script>
$('.shorten').each(function() {
while (
// didn't use jQuery here cause I think it's slightly faster to use JS when you can
// "20" is the normal height, so if it's more then it wrapped
this.parentNode.offsetHeight > 20 &&
// minimum length will be 7 so that there's at least 1 character at the beginning
// and end of the ... If that's not good enough, give up anyway
$(this).html().length > 7)
$(this).html(abbr($(this).html()));
});
function abbr(str) {
return str.replace(
str.substr(
parseInt(str.length / 2) - 3,
5
), '...');
}
</script>
I hate putting things in a loop like that, especially when it can be a relatively long page with a lot of ".shorten" classes. What do you guys and gals think, is there a "better" way to do this?