I want to calculate width in px for given text in span element. I check several answers in Stackoverflow. However nothing work for me :(. I am trying to figure out what I am doing wrong. Here is jsFiddle link. And here is code:
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(html_calc).css('font-size', this.css('font-size'));
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
var ts_name = $('span#ts_name');
var ts_name_text=ts_name.text().trim();
var ts_name_p_box_width = $('div#container-testset-name').innerWidth()-100;
var text_width = $(ts_name).textWidth();
My result for text_p_box_width is 737px and for text_width 715px. However it is clear from html view in Chrome browser text size is bigger than its container. SO what is my mistake? Thank you in advance.
P.S. If you need some clarification please leave as comment.
Edit: I saw similar answer of @LeeTaylor in other question. However it doesn't solve my problem. Because in my case text inside of span element. But in your case text inside of div. I can not change span's display property to block. So for my case this does not work. I tried to generate dynamically two elements using jQuery and try to fetch width. But it is 0. I found that since this dynamically created objects does not included to DOM tree and CSS not applied it will work.
`var ts_name=$('span#ts_name').text().trim();
var text_container = $(document.createElement('span')).html(ts_name).attr('id', 'input_text');
var block_container = $(document.createElement('div')).html(text_container).css({display:'block'});
block_container.css({width: '3000px'});
console.log($(block_container).find('span#input_text').width());
console.log($(block_container).find('span#input_text').outerWidth());
console.log($(block_container).find('span#input_text').innerWidth());
I did because I want to use your solution however it does not work. So do you have any idea on that?
SOLUTION: I figure out why my code is not working I just change only one value in css like this:
div#ts_designer>div#container-testset-name.c-group-inner-row span#ts_name
{
position: absolute;
left: 100px;
right: 0;
top: 0px;
bottom: 0;
width: auto!important;
white-space: nowrap; /*This line added*/
}
Here is updated jsFiddle link.
P.S. I will up vote your answers as reward to your answers. However I cannot accept one of them.