views:

57

answers:

2

Hello folks,

I need to know how one can get the maximum possible width of a div. Generally, a <div>'s width is limited by it's parent, meaning that it can not be larger than a certain amount. How that certain amount can be calculated?

I need this to calculate if the text inside the current <div> has overflown, (since the only way to detect a text overflow is to compare it's current width to its current clientWidth).

Thanks!

+1  A: 

A couple ways to do this, let's start with your div...

<div id='mr_cleaver'>
  <div id='beaver'>Blah</div>
</div>

...and then someJavascript:

//Method One: Find the width of the div's parent
var max_beaver_width = $('mr_cleaver').offsetWidth

//Method Two: Max out the div, find length, return to original size.
var beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = "100%';
var max_beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = beaver_width + 'px';

//Method Three: Check for overflow
$('beaver').scrollWidth > $('beaver').offsetWidth ? alert("Over") : alert("Within")
Steve
Thanks Steve!Your suggestions were very helpful. Although none of them worked for me(probably I didn't explain my situation very well), but I could find a way to detect text overflow:/* specifying the height of 'beaver'*/var font_size= $('beaver').css("font-size");font_size = parseInt(font_size.replace(/[a-z]*/gi,''));var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight/*now calculate current height*/$('beaver').style.overflow-y:visible;$('beaver').style.overflow-x:hidden;if(elem.clientHeigth > maxHeight){ //overflow has been occured}
green-i
A: 

Thanks Steve!

Your suggestions were very helpful. Although none of them worked for me(probably I didn't explain my situation very well), but using your hints, I could find a way to detect text overflow:

/* specifying the height of 'beaver'*/
var font_size= $('beaver').css("font-size");
font_size = parseInt(font_size.replace(/[a-z]*/gi,''));
var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight

/*now calculate current height*/
$('beaver').style.overflow-y:visible;
$('beaver').style.overflow-x:hidden;
var cuurentHeight = $('beaver').clientHeigth;

/* check whether overflow is occured*/
if(cuurentHeight > maxHeight){
    //overflow has been occured
}
green-i