Skip to content

Instantly share code, notes, and snippets.

@lgoldstien
Created July 7, 2014 11:36
Show Gist options
  • Save lgoldstien/45c35709f804d6267917 to your computer and use it in GitHub Desktop.
Save lgoldstien/45c35709f804d6267917 to your computer and use it in GitHub Desktop.
/**
* textWidth
* Get the pixel width of a string before rendering it in the DOM, requires jQuery global
*
* @param {string} - The text string you want the pixel width of
* @param {string} - Any classes that need to be taken into account when calculating
*
* @return {integer} - The width in pixels of the text string
*/
var textWidth = function (string, classes) {
var width, $elem = $('<span></span>');
$elem.addClass(classes);
$elem.attr("style", "position: absolute;top: -999px;left: -999px;");
$elem.text(string);
$('body').append($elem);
width = $elem.width();
$elem.remove();
return width;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment