detecting line-breaks with jQuery?

I came up with an approach, but it might be overkill for your purposes, so take this into account.

You need to create a clone of the element, empty the original, then move each word back into the original element. If the height changes at any point, there’s a line-break before that word. This would be fairly simple to do using $(el).text(), but it gets more complicated if there can be other tags inside, not just text. I tried explaining how to break it down by node in this answer box, but found it easier just to create a jQuery plugin in a jsFiddle. Link here: http://jsfiddle.net/nathan/qkmse/ (Gist).

It won’t handle floated elements all that well, and there are a few other situations where it’ll fall over. Let me know if you’d like more options, or if it doesn’t quite work for your purposes, or if you’re not sure how to apply it and I’ll try to help.

Leave a Comment