Reputation: 2874
(HTML) Let's say I have within fixed-width containers. Some of these headings will be longer than one line. I would like isolate these lines and do separate things to each line. Is there a way, with JavaScript, to calculate where the heading has broken to the next line and to for example put a span around each line?
Upvotes: 3
Views: 217
Reputation: 4646
Hacky and dirty: render the same string in the same container char-by-char until it doesn't fit, then take this string and wrap it in a <span>
, repeat.
$(function(){
$h = $('.fixed').find('h3');
$h.each(function(i,e){
var txt = $(e).text();
$th = $('<h3 />').prependTo($(e).parent());
var lh = $(e).text('X').height();
$(e).text('');
while (txt.length > 0) {
$th.text($th.text() + txt[0]);
txt = txt.slice(1);
if (($th.height() > lh) || (txt.length <= 0)) {
var shc = $th.text().split(' ');
var ph = shc.slice(0,-1).join(' ')+' ';
if (txt.length <= 0) { ph += shc.pop(); }
$('<span />').text(ph).appendTo($(e));
$th.text(shc.pop());
}
}
$th.remove();
})
});
There are some limitations in usage. For example, headings aren't expected to contain anything but plain text - any HTML tags will be stripped off.
And there is, of course, fiddle for this.
Upvotes: 1
Reputation: 237975
I've written a slightly hacky custom selector. This selector clones the object, then gives the clone the HTML A
. It then compares heights of the original and the clone. If they are the same or the copy is bigger, the selector fails. If the copy is smaller than the original (i.e. we presume the line has wrapped), the selector passes:
$.expr[':'].multiLine = function(obj) {
var $this = $(obj),
copy = $this.clone().html('A').insertAfter($this)
ret;
ret = (copy.height() < $this.height());
copy.remove();
return ret;
};
You can call this like this:
$('h1:multiLine')
NB that you should not wrap h*
elements in span
tags, because inline elements (e.g. span
) may not contain block-level elements (e.g. h1
).
Edit Note also that this may not work if you have images in your header, or if you change the height of any text within the header. It's probably best not to rely on this kind of detection -- use it for enhancement only.
Upvotes: 0