I\'m trying to calculate text width using jQuery. I\'m not sure what, but I am definitely doing something wrong.
So, here is the code:
var c = $(\'.c
Here's a function that's better than others posted because
<input>
, <span>
, or "string"
.Demo: http://jsfiddle.net/philfreo/MqM76/
// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
i think you should use $('.calltoaction').val;
also, i would be using id (#) instead of a class for that.. if u have more than one of such classes which how would it handle it?
Neither Rune's nor Brain's was working for me in case when the element that was holding the text had fixed width. I did something similar to Okamera. It uses less selectors.
EDIT:
It won't probably work for elements that uses relative font-size
, as following code inserts htmlCalc
element into body
thus looses the information about parents relation.
$.fn.textWidth = function() {
var htmlCalc = $('<span>' + this.html() + '</span>');
htmlCalc.css('font-size', this.css('font-size'))
.hide()
.prependTo('body');
var width = htmlCalc.width();
htmlCalc.remove();
return 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