Answer by Chris Petersn for Calculating text width

I had trouble with solutions like @rune-kaagaard's for large amounts of text. I discovered this:

$.fn.textWidth = function() {
	var width = 0;
	var calc = '<span style="display: block; width: 100%; overflow-y: scroll; white-space: nowrap;" class="textwidth"><span>' + $(this).html() + '</span></span>';
	$('body').append(calc);
	var last = $('body').find('span.textwidth:last');
	if (last) {
			var lastcontent = last.find('span');
			width = lastcontent.width();
			last.remove();
	}
	return width;
};

JSFiddle GitHub


Wednesday 14th November 2018 12:14 am

Back to User Chris Petersn - Stack Overflow blog