SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Setting Div Height

    Is there a way you can find out the height of a div and then set the style height to that value? I'm using a animated collapsing div effect, but it needs to know the height of the div. It works if you set it statically knowing the height ahead of time. But if you load in dynamic text, doesn't work so good. So wondering if there is a way to set it dynamically?

  2. #2
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Does this example work for you?

    Also, I noticed that it doesn't calculate borders - at least not in firefox.

    Code:
    <html>
    <head>
    <title>test</title>
    <script language="javascript" type="text/javascript">
    function calculateHeight() {
    	var newHeight = document.getElementById('content').clientHeight;
    	alert(newHeight);
    }
    </script>
    </head>
    <body onLoad="calculateHeight();">
    <div id="content">
    this<br>
    is<br>
    dynamic<br>
    lol
    </div>
    </div>
    </body>
    </html>
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How would I set it though? I'm hoping the script that is collapsing the div even recognizes it. I tried setting it by:

    Code:
    var newHeight = document.getElementById('testdiv').clientHeight;
    document.testdiv.style.height= newHeight;
    But that completely breaks the collapsing function.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well it returns the height of the div without 'px' at the end, also inside of the script running this animation is where I would calculate the height variable and use it, the height of the div is already set at that value and your script probably will not reflect the change.

    I'm not great with javascript but if your animation script requires the height measurement you'll want the variable to be equal to:

    newHeight + ' px';
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I thank you for the help, not awesome at JS either. Here is what I'm using, just not sure how to set the height then. The script is called by slideup(divname);

    Code:
    var timerlen = 5;
    var slideAniLen = 250;
    
    var timerID = new Array();
    var startTime = new Array();
    var obj = new Array();
    var endHeight = new Array();
    var moving = new Array();
    var dir = new Array();
    
    function slidedown(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display != "none")
                    return; // cannot slide down something that is already visible
    
            moving[objname] = true;
            dir[objname] = "down";
            startslide(objname);
    }
    
    function slideup(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display == "none")
                    return; // cannot slide up something that is already hidden
    
            moving[objname] = true;
            dir[objname] = "up";
            startslide(objname);
    }
    
    function startslide(objname){
            obj[objname] = document.getElementById(objname);
    
            endHeight[objname] = parseInt(obj[objname].style.height);
            startTime[objname] = (new Date()).getTime();
    
            if(dir[objname] == "down"){
                    obj[objname].style.height = "1px";
            }
    
            obj[objname].style.display = "block";
    
            timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
    }
    
    function slidetick(objname){
            var elapsed = (new Date()).getTime() - startTime[objname];
    
            if (elapsed > slideAniLen)
                    endSlide(objname)
            else {
                    var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                    if(dir[objname] == "up")
                            d = endHeight[objname] - d;
    
                    obj[objname].style.height = d + "px";
            }
    
            return;
    }
    
    function endSlide(objname){
            clearInterval(timerID[objname]);
    
            if(dir[objname] == "up")
                    obj[objname].style.display = "none";
    
            obj[objname].style.height = endHeight[objname] + "px";
    
            delete(moving[objname]);
            delete(timerID[objname]);
            delete(startTime[objname]);
            delete(endHeight[objname]);
            delete(obj[objname]);
            delete(dir[objname]);
    
            return;
    }

  6. #6
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's my test page I created, html and javascript - I only changed one section of your code "1px" to 1 + 'px':

    Code:
    <html>
    <head>
    <title>test</title>
    <script language="javascript" type="text/javascript">
    var timerlen = 5;
    var slideAniLen = 250;
    
    var timerID = new Array();
    var startTime = new Array();
    var obj = new Array();
    var endHeight = new Array();
    var moving = new Array();
    var dir = new Array();
    
    function slidedown(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display != "none")
                    return; // cannot slide down something that is already visible
    
            moving[objname] = true;
            dir[objname] = "down";
            startslide(objname);
    }
    
    function slideup(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display == "none")
                    return; // cannot slide up something that is already hidden
    
            moving[objname] = true;
            dir[objname] = "up";
            startslide(objname);
    }
    
    function startslide(objname){
            obj[objname] = document.getElementById(objname);
    
            endHeight[objname] = parseInt(obj[objname].style.height);
            startTime[objname] = (new Date()).getTime();
    
            if(dir[objname] == "down"){
                    obj[objname].style.height = 1 + 'px';
            }
    
            obj[objname].style.display = "block";
    
            timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
    }
    
    function slidetick(objname){
            var elapsed = (new Date()).getTime() - startTime[objname];
    
            if (elapsed > slideAniLen)
                    endSlide(objname)
            else {
                    var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                    if(dir[objname] == "up")
                            d = endHeight[objname] - d;
    
                    obj[objname].style.height = d + 'px';
            }
    
            return;
    }
    
    function endSlide(objname){
            clearInterval(timerID[objname]);
    
            if(dir[objname] == "up")
                    obj[objname].style.display = "none";
    
            obj[objname].style.height = endHeight[objname] + "px";
    
            delete(moving[objname]);
            delete(timerID[objname]);
            delete(startTime[objname]);
            delete(endHeight[objname]);
            delete(obj[objname]);
            delete(dir[objname]);
    
            return;
    }
    </script>
    </head>
    
    <body>
    <div style="height:20px;width:600px;margin:auto;background:blue;" onMouseOver="slidedown('slide2')">
    this should slide div 'slide2' down
    </div>
    <div style="height:200px;width:600px;margin:auto;background:yellow;display:none;" id="slide2" onMouseOut="slideup('slide2')">
    new div
    </div>
    </body>
    </html>
    Here's the js only

    Code:
    var timerlen = 5;
    var slideAniLen = 250;
    
    var timerID = new Array();
    var startTime = new Array();
    var obj = new Array();
    var endHeight = new Array();
    var moving = new Array();
    var dir = new Array();
    
    function slidedown(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display != "none")
                    return; // cannot slide down something that is already visible
    
            moving[objname] = true;
            dir[objname] = "down";
            startslide(objname);
    }
    
    function slideup(objname){
            if(moving[objname])
                    return;
    
            if(document.getElementById(objname).style.display == "none")
                    return; // cannot slide up something that is already hidden
    
            moving[objname] = true;
            dir[objname] = "up";
            startslide(objname);
    }
    
    function startslide(objname){
            obj[objname] = document.getElementById(objname);
    
            endHeight[objname] = parseInt(obj[objname].style.height);
            startTime[objname] = (new Date()).getTime();
    
            if(dir[objname] == "down"){
                    obj[objname].style.height = 1 + 'px';
            }
    
            obj[objname].style.display = "block";
    
            timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
    }
    
    function slidetick(objname){
            var elapsed = (new Date()).getTime() - startTime[objname];
    
            if (elapsed > slideAniLen)
                    endSlide(objname)
            else {
                    var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                    if(dir[objname] == "up")
                            d = endHeight[objname] - d;
    
                    obj[objname].style.height = d + 'px';
            }
    
            return;
    }
    
    function endSlide(objname){
            clearInterval(timerID[objname]);
    
            if(dir[objname] == "up")
                    obj[objname].style.display = "none";
    
            obj[objname].style.height = endHeight[objname] + "px";
    
            delete(moving[objname]);
            delete(timerID[objname]);
            delete(startTime[objname]);
            delete(endHeight[objname]);
            delete(obj[objname]);
            delete(dir[objname]);
    
            return;
    }
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  7. #7
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oh you know what, I just set the height manually by the div already. <smacks forhead>
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  8. #8
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's some code I found during a search but I don't understand why offsetHeight is not giving me the div height correctly, showing as 0.

    Code:
    //Animated Collapsible DIV- Author: Dynamic Drive (http://www.dynamicdrive.com)
    //Last updated June 27th, 07'. Added ability for a DIV to be initially expanded.
    
    var uniquepageid=window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, "") //get current page path and name, used to uniquely identify this page for persistence feature
    
    function animatedcollapse(divId, animatetime, persistexpand, initstate){
    	this.divId=divId
    	this.divObj=document.getElementById(divId)
    	this.divObj.style.overflow="hidden"
    	this.timelength=animatetime
    	this.initstate=(typeof initstate!="undefined" && initstate=="block")? "block" : "contract"
    	this.isExpanded=animatedcollapse.getCookie(uniquepageid+"-"+divId) //"yes" or "no", based on cookie value
    	this.contentheight=parseInt(this.divObj.style.height)
    	var thisobj=this
    	if (isNaN(this.contentheight)){ //if no CSS "height" attribute explicitly defined, get DIV's height on window.load
    		animatedcollapse.dotask(window, function(){thisobj._getheight(persistexpand)}, "load")
    		if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
    			this.divObj.style.visibility="hidden" //hide content (versus collapse) until we can get its height
    	}
    	else if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
    		this.divObj.style.height=0 //just collapse content if CSS "height" attribute available
    	if (persistexpand)
    		animatedcollapse.dotask(window, function(){animatedcollapse.setCookie(uniquepageid+"-"+thisobj.divId, thisobj.isExpanded)}, "unload")
    }
    
    animatedcollapse.prototype._getheight=function(persistexpand){
    	this.contentheight=this.divObj.offsetHeight
    	if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes"){ //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
    		this.divObj.style.height=0 //collapse content
    		this.divObj.style.visibility="visible"
    	}
    	else //else if persistence is enabled AND this content should be expanded, define its CSS height value so slideup() has something to work with
    		this.divObj.style.height=this.contentheight+"px"
    }
    
    
    animatedcollapse.prototype._slideengine=function(direction){
    	var elapsed=new Date().getTime()-this.startTime //get time animation has run
    	var thisobj=this
    	if (elapsed<this.timelength){ //if time run is less than specified length
    		var distancepercent=(direction=="down")? animatedcollapse.curveincrement(elapsed/this.timelength) : 1-animatedcollapse.curveincrement(elapsed/this.timelength)
    	this.divObj.style.height=distancepercent * this.contentheight +"px"
    	this.runtimer=setTimeout(function(){thisobj._slideengine(direction)}, 10)
    	}
    	else{ //if animation finished
    		this.divObj.style.height=(direction=="down")? this.contentheight+"px" : 0
    		this.isExpanded=(direction=="down")? "yes" : "no" //remember whether content is expanded or not
    		this.runtimer=null
    	}
    }
    
    
    animatedcollapse.prototype.slidedown=function(){
    	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
    		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
    			alert("Please wait until document has fully loaded then click again")
    		else if (parseInt(this.divObj.style.height)==0){ //if content is collapsed
    			this.startTime=new Date().getTime() //Set animation start time
    			this._slideengine("down")
    		}
    	}
    }
    
    animatedcollapse.prototype.slideup=function(){
    	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
    		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
    			alert("Please wait until document has fully loaded then click again")
    		else if (parseInt(this.divObj.style.height)==this.contentheight){ //if content is expanded
    			this.startTime=new Date().getTime()
    			this._slideengine("up")
    		}
    	}
    }
    
    animatedcollapse.prototype.slideit=function(){
    	if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
    		alert("Please wait until document has fully loaded then click again")
    	else if (parseInt(this.divObj.style.height)==0)
    		this.slidedown()
    	else if (parseInt(this.divObj.style.height)==this.contentheight)
    		this.slideup()
    }
    
    // -------------------------------------------------------------------
    // A few utility functions below:
    // -------------------------------------------------------------------
    
    animatedcollapse.curveincrement=function(percent){
    	return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
    }
    
    
    animatedcollapse.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
    	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
    	if (target.addEventListener)
    		target.addEventListener(tasktype, functionref, false)
    	else if (target.attachEvent)
    		target.attachEvent(tasktype, functionref)
    }
    
    animatedcollapse.getCookie=function(Name){ 
    	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
    	if (document.cookie.match(re)) //if cookie found
    		return document.cookie.match(re)[0].split("=")[1] //return its value
    	return ""
    }
    
    animatedcollapse.setCookie=function(name, value, days){
    	if (typeof days!="undefined"){ //if set persistent cookie
    		var expireDate = new Date()
    		var expstring=expireDate.setDate(expireDate.getDate()+days)
    		document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()
    	}
    	else //else if this is a session only cookie
    		document.cookie = name+"="+value
    }
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  9. #9
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I thought maybe it was because the height script was above the div and it was zero at that moment, so set it below the dive and the animation of the up stops and the down just breaks. Frustrating, is there a way to set the inline style directly, but not statically?

  10. #10
    SitePoint Enthusiast
    Join Date
    Jul 2007
    Location
    Virginia
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    style.display = 'inline'; ?

    Yeah this is a pain, nice project =D

    Wish someone else would tune in to the discussion I'd like to see the rest of the script made.
    Mark A. Drake
    - Mark A. Drake
    - OnSlaught

  11. #11
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I'd think with all the knowledgeable people on here, this wouldn't be a huge problem. But with all the views and no other input, maybe it is, lol. I'll keep trying and thanks for your suggestions.

    --Edit--

    Well I fixed it, thanks for all your help and suggestions
    Last edited by 700lbGorilla; Aug 2, 2007 at 14:44. Reason: Solved


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •