Hello,
Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ?
I mean the visual line, the browser computed line, and not the line in the source code .
Hello,
Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ?
I mean the visual line, the browser computed line, and not the line in the source code .
Well, there's a way to guesstimate it, and it's not pretty, but I've used it before.
The algorithm basically goes like this:
It's not pretty but it works if you duplicate the elements right.
jQuery.fn.line = function(line) {
var dummy = this.clone().css({
top: -9999,
left: -9999,
position: 'absolute',
width: this.width()
}).appendTo(this.parent()),
text = dummy.text().match(/\S+\s+/g);
var words = text.length,
lastTopOffset = 0,
lineNumber = 0,
ret = '',
found = false;
for (var i = 0; i < words; ++i) {
dummy.html(
text.slice(0,i).join('') +
text[i].replace(/(\S)/, '$1<span/>') +
text.slice(i+1).join('')
);
var topOffset = jQuery('span', dummy).offset().top;
if (topOffset !== lastTopOffset) {
lineNumber += 1;
}
lastTopOffset = topOffset;
if (lineNumber === line) {
found = true;
ret += text[i];
} else {
if (found) {
break;
}
}
}
dummy.remove();
return ret;
};
$('#someParagraph').line(3); // blah blah blah
Example: http://jsbin.com/akave
It goes through the entire element (actually, a clone of the element) inserting a <span/>
element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.