Skip to content

Instantly share code, notes, and snippets.

@guacamoli
Last active October 24, 2017 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guacamoli/859d7853c137b905dc4dc950186d3a22 to your computer and use it in GitHub Desktop.
Save guacamoli/859d7853c137b905dc4dc950186d3a22 to your computer and use it in GitHub Desktop.
Helper to figure out if a rendered element is truncated
// Working example in jsfiddle: https://jsfiddle.net/Ld2pjabu/5/
// Helper to get the width of any element
function getElementWidth(element) {
return (element && element.getBoundingClientRect) ? element.getBoundingClientRect().width : 0;
}
// Helper to calculate an unbound width
function getUnboundWidth(element) {
// Clone the element in question
var clonedElement = element.cloneNode(true);
// Add inline styles to make the element extend to the width it needs
clonedElement.style.width = 'auto';
clonedElement.style.visibility = 'hidden';
// Append the element to the body to be rendered
document.body.append(clonedElement);
var elementWidth = getElementWidth(clonedElement);
// Remove the cloned element from the DOM
clonedElement.parentNode.removeChild(clonedElement);
return elementWidth;
}
// Returns true or false depending on if the element as currently renedered is truncated
function isTruncatedElement(element) {
var renderedWidth = getElementWidth(element);
var fullWidth = getUnboundWidth(element)
return (renderedWidth < fullWidth);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment