Alexandre Jaquet wrote:
Hi,
I'm looking for the way to resize an element when the page loading.
I'm doing some test and I've try :
function placeHeader () {
var x;
document.getElementById('header').style.display = 'visible';
for (x = 0; x < 150;x++) {
document.getElementById('header').style.width = x + "px";
}
}
but nothing appear
Any idea thx in advance
function placeHeader () {
var ele = document.getElementById('header');
if ( ele && ele.style ){
ele.style.display = '';
for (var x=0; x<150; x++) {
ele.style.width = x + "px";
}
}
}
1. Checks that getElementById returned something
2. Checks that whatever ele is, it supports the style object
3. Makes one call to getElementById, not 152 as in the original
So should be more robust and use fewer CPU resources. However, given
that there is no lag between each loop, it will run so quickly that
most visitors will not see the element grow, it will just appear to
be full size straight up.
If you want it to "grow", you have to use setTimeout with a suitable
value (say 10 milliseconds) then the element 'header' will take about
1.5 seconds to reach full size. To get a faster transition, use
bigger steps.
Here's an example based on one I baked earlier:
<script type="text/javascript">
function growEle(z){
if (document.getElementById) {
var el = document.getElementById(z);
} else {return}
if ( el && el.style ){
var w = 0;
var maxWidth = 150; // Max width of element
var d = 10; // Delay between steps
var s = 5; // Step to grow by
// Stop timer if it's already running
if (el.timer) window.clearTimeout(el.timer);
el.timer = window.setInterval(function(){ // Start timer
if ( w > maxWidth ) { // If reached limit
el.style.width = maxWidth + 'px'; // Set width to limit
window.clearTimeout(el.timer); // Stop timer
el.timer = null; // Clear timer
}
el.style.width = w + 'px'; // Set the width
w += s; // Increment width
}, d); // End timer
}
}
</script>
<input type="button" value="Grow 'header'" onclick="
growEle('header');
">
<div style="border: 1px solid red; width: 10px;" id="header">blah
</div>
--
Rob