PDA

View Full Version : simple gradual div height change - something wrong with this script!


wuffy77
02-05-2008, 04:15 PM
Can anyone tell me what I've done daft with this script?


I'm trying to get the div height to gradually increase on loading the page? It works but it's just suddenly appearing.


<html>
<head>

<script type='text/javascript'>
function setdistance()
{
var distance = 300; //distance in miles
var distancepixels = 500; //height of route in pixels
var distancemiles = 750; //distance of the jouney in miles
for (i=0; i<=distance; i++)
{
progress=(distancemiles/distancepixels)*i;
document.getElementById('route').style['height']=progress;
}

}
</script>

<style>
.mapbg
{
width: 300px;
background-color: red;
}
</style>

</head>
<body onload="setInterval('setdistance()', 500)">

<div class="mapbg" id="route" style="height:0px">
<img src="file:///J:/1. Katie's Work/RBS/RER charity walk/map.png">

</div>
</body>
</html>

coothead
02-06-2008, 04:23 AM
Hi there wuffy77,

1. Your main error is the the for statement.

Every 500ms the script runs the for statement, thus taking the div height to 450px.

You want a gradual increment which means the use of i++.

2. The document.getElementById('route').style['height']=progress; statement will not work when a valid DOCTYPE is used.

3. It is preferable to place the onload event within the script.

4. There is no need for inline CSS.

Here are the highlighted amendments...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
#route {
width:300px;
height:0;
background-color:#f00;
}
</style>

<script type="text/javascript">

var i=0;

function setdistance() {

distance=300; //distance in miles
distancepixels=500; //height of route in pixels
distancemiles=750; //distance of the journey in miles

i++;
if(i>distance) {
return;
}

progress=(distancemiles/distancepixels)*i;
document.getElementById('route').style['height']=progress+'px';

}
window.onload=function() {
setInterval('setdistance()',500);
}
</script>

</head>
<body>

<div id="route">
<img src="file:///J:/1. Katie's Work/RBS/RER charity walk/map.png" alt="">
</div>

</body>
</html>


I hope that this helps. :agree:

wuffy77
02-06-2008, 04:49 AM
'hope this helps' indeed! Of course it helps! - genius stuff!

Thanks very much - much clearer now! ;)

coothead
02-06-2008, 05:23 AM
No problem, you're very welcome. :agree: