Last active
October 24, 2017 23:49
-
-
Save guacamoli/859d7853c137b905dc4dc950186d3a22 to your computer and use it in GitHub Desktop.
Helper to figure out if a rendered element is truncated
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
// 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