Skip to content

Instantly share code, notes, and snippets.

@jaridmargolin
Last active December 28, 2015 01:19
Show Gist options
  • Save jaridmargolin/7420132 to your computer and use it in GitHub Desktop.
Save jaridmargolin/7420132 to your computer and use it in GitHub Desktop.
Get text length
//
// Get text width of a specified element.
//
function measureWidth(el, str) {
// Create dummy elem
var div = documtent.createElement('div');
// Append
document.body.appendChild(div);
// Mirror input
var styles = window.getComputedStyle(el).cssText;
div.setAttribute("style", styles);
// Setup to grab width
div.style.width = "auto";
div.style.position = "absolute";
div.style.left = '-1000px';
div.style.top = '-1000px';
div.innerHTML = str;
// Get width
var result = div.clientWidth;
// Clean up
document.body.removeChild(div);
div = null;
// Return result
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment