Smooth height change

Discussion in 'JavaScript' started by ::Mike::, Apr 25, 2009.

  1. #1
    function $(id){
    	return document.getElementById(id);
    }
    function ComputedStyle(id,value){
    	return document.defaultView.getComputedStyle($(id), "").getPropertyValue(value);
    }
    function setheight(id,a){
    	$(id).style.height=a+'px';
    }
    function slide(id,duration){
    	height1 = ComputedStyle(id,'height').replace('px','');
    	i=parseInt(height1);
    	while(i > 0){
    		setTimeout("setheight('"+id+"',"+i+")",i*duration);
    		i=i-1;
    	}
    }
    Code (markup):
    i seems to get to 0 when I'm debugging but it doesn't change the actual height!
    But then when it hits 0 it seems to change the height to 0 then smoothly make the box bigger to the original height!!
    but I want it to start at 100px then smoothly close to 0px.

    Anyone got any ideas on what I'm doing wrong?
     
    ::Mike::, Apr 25, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    erm here is what's happening...

    you run a loop that pre-queues your setTimeouts for you based upon data available at the time of the loop, namely i being between 100 and 0.

    However, by the time the setTimeout hits and starts executing, i is already 0 so it goes to -1, -2 etc.

    you need to self reference from your function to ensure a measured and timely execution...

    not tested this but for example:
    <div id="foo" style="background: red; width: 200px; height: 100px"></div>
    <script>
    var reduceDelay = 1, reduceStep = 5, reduceHeight = function(id) {
        var el = document.getElementById(id), i = parseInt(el.style.height);
        if (i >= 0) {
            el.style.height = i - reduceStep + "px";
            setTimeout("reduceHeight('"+id+"');", reduceDelay * i);
        }
    };
    
    
    window.onload = function() {
        reduceHeight("foo");
    };
    </script>
    PHP:
     
    dimitar christoff, Apr 27, 2009 IP
  3. ::Mike::

    ::Mike:: Peon

    Messages:
    826
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Brilliant, Thanks it worked 1st time!
     
    ::Mike::, Apr 27, 2009 IP