October 29th, 2013, 03:08 AM
-
Fixed size div
I am trying to create a div element with fixed size in html. My problem is, the above div receives input text from javascript. The size of text is unknown, so every time that the transmitted text is big, automatically the size of the div is change. How is it possible to display only the first words of the text that fit in the predefined size of the div???
October 29th, 2013, 05:33 AM
-
Javascript Code:
var str = "Random string of randomness.";
var strMax = 20;
var strOut = str.length > strMax ? str.substring(0,strMax) : str;
alert(strOut);
Last edited by Winters; October 29th, 2013 at 05:36 AM.
Reason: typo
October 29th, 2013, 07:05 AM
-
The problem is that since the font size is not static, you cant define maxsize as a constant. So i want to dissapear my text that dont fit in div and gets out of div bounding box.
October 30th, 2013, 06:05 AM
-
What you are asking for is possible but would end up becoming a very obese script for such a simple function.
Here it is..CSS Code:
span#tmp {
position: absolute;
top: -5000px;
}
Javascript Code:
var str = "Random string of random words!";
var max = 100;
onload = function() {
var strTmp = document.getElementById('tmp');
strTmp.innerHTML = str;
if (strTmp.offsetWidth > max) {
var strTrim = str.substring(0, str.length-3);
while (strTmp.offsetWidth > max) {
strTrim = strTrim.substring(0, strTrim.length-1);
strTmp.innerHTML = strTrim + "...";
}
}
document.getElementById('txt').innerHTML = strTmp.innerHTML;
}
If you want to make that more efficient, you can compare the maximum width to the current width and use more complex methods to shorten the looping. If you want to use line breaks and height, that is something else altogether.