Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active December 29, 2015 02:51
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save barneycarroll/5264274 to your computer and use it in GitHub Desktop.
Count the number of lines of text in a given element.
void function $getLines($){
function countLines($element){
var lines = 0;
var greatestOffset = void 0;
$element.find('character').each(function(){
if(!greatestOffset || this.offsetTop > greatestOffset){
greatestOffset = this.offsetTop;
++lines;
}
});
return lines;
}
$.fn.getLines = function $getLines(){
var lines = 0;
var clean = this;
var dirty = this.clone();
(function wrapCharacters(fragment){
var parent = fragment;
$(fragment).contents().each(function(){
if(this.nodeType === Node.ELEMENT_NODE){
wrapCharacters(this);
}
else if(this.nodeType === Node.TEXT_NODE){
void function replaceNode(text){
var characters = document.createDocumentFragment();
text.nodeValue.replace(/[\s\S]/gm, function wrapCharacter(character){
characters.appendChild($('<character>' + character + '</>')[0]);
});
parent.replaceChild(characters, text);
}(this);
}
});
}(dirty[0]));
clean.replaceWith(dirty);
lines = countLines(dirty);
dirty.replaceWith(clean);
return lines;
};
}(jQuery);
@barneycarroll
Copy link
Author

Buggy! Counts 1 line minimum, misses lines for certain cases of elaborated nested content. Maybe to do with mono-space.

@barneycarroll
Copy link
Author

Possible solution to problem above: store container's offsetTop add another line for each different <character/> offsetTop that isn't equal to the parent's?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment