Skip to content

Instantly share code, notes, and snippets.

@keidrun
Created May 10, 2020 23:29
Show Gist options
  • Save keidrun/c86608db2f7e0d802ece775e1effefc2 to your computer and use it in GitHub Desktop.
Save keidrun/c86608db2f7e0d802ece775e1effefc2 to your computer and use it in GitHub Desktop.
Calculate the text width using jQuery
$(function () {
var $target = $('#target');
var text = $target.text();
text.split('').forEach((str) => {
console.log(str + "'s length is " + textWidth($target, str));
});
});
/**
* Calculate the width of the text in the element
* @param {jQuery Object} element - the element
* @param {string} text - the text in the element
* @returns {float} the text width
*/
function textWidth(element, text) {
$element = $(element);
var span = $('<span>').hide().append(text);
$element.append(span);
var width = span.width();
$element.find('span:first').remove();
return width;
}
// Just a bit refer to https://stackoverflow.com/questions/1582534/calculating-text-width
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment