tags:

views:

1526

answers:

5

Hi.

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 = $('.calltoaction');

var cTxt = c.text();

var cWidth =  cTxt.outerWidth();

c.css('width' , cWidth);

Thank you for your help in advance!

A: 

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?

Noam Smadja
Yes, there is more then one in document. Why would you suggest id?
Dom
+2  A: 

the thing, you are doing wrong, that you are calling a method on cTxt, which is a simple string and not a jQuery object. cTxt is really the contained text.

Juraj Blahunka
Right. Thanks a lot!
Dom
+4  A: 

jQuery's width functions can be a bit shady when trying to determine the text width due to inconsistent box models. The sure way would be to inject div inside your element to determine the actual text width:

$.fn.textWidth = function(){
  var sensor = $('<div />').css({margin: 0, padding: 0});
  $(this).append(sensor);
  var width = sensor.width();
  sensor.remove();
  return width;
};

To use this mini plugin, simply:

$('.calltoaction').textWidth();
brianreavis
Wouldn't this give you the block width rather than the text?
CaffeineFueled
+2  A: 

This worked better for me:

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>'
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};
runish
A: 

If your trying to do this with text in a select box or if those two arent working try this one instead:

$.fn.textWidth = function(){
 var calc = '<span style="display:none">' + $(this).text() + '</span>';
 $('body').append(calc);
 var width = $('body').find('span:last').width();
 $('body').find('span:last').remove();
 return width;
};

or

function textWidth(text){
 var calc = '<span style="display:none">' + text + '</span>';
 $('body').append(calc);
 var width = $('body').find('span:last').width();
 $('body').find('span:last').remove();
 return width;
};

if you want to grab the text first

okamera