Count the number of lines of text in a given element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
Buggy! Counts 1 line minimum, misses lines for certain cases of elaborated nested content. Maybe to do with mono-space.