Thread: Fixed size div

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    8
    Rep Power
    0

    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???
  2. #2
  3. No Profile Picture
    Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,008
    Rep Power
    2791
    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
    [PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [ANSI C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]

    W3Fools - A W3Schools Intervention.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    8
    Rep Power
    0
    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.
  6. #4
  7. No Profile Picture
    Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,008
    Rep Power
    2791
    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;
    }
    HTML4Strict Code:
    <span id="tmp"></span>
    <div id="txt"></div>
    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.
    [PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [ANSI C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]

    W3Fools - A W3Schools Intervention.

IMN logo majestic logo threadwatch logo seochat tools logo