Forum Moderators: open

Message Too Old, No Replies

Using loops and time delays to create transitions between widths

         

Jeremy_H

3:06 pm on Oct 23, 2006 (gmt 0)

10+ Year Member



I'm trying to change the width of an input field on click.

I want a fluid transition between the starting width and the ending width, so I created a loop that will increase the width by 1-pixel every fraction of a second, until it reaches the desired width.

Unfortunatly, all that happens is it waits a fraction of a second, then it jumps to the second width.

I haven't worked with setTimeout before. Is there something I'm doing wrong?

Thanks

function s(){
var s=document.getElementById("input");
if(s.value=="Input"){
s.value="";
for(i=35;i<200;i++) setTimeout("document.getElementById('input').style.width=i+'px';",500);
}
}

<input type="text" name="q" value="Input" id="input" onclick="return s();" onblur="return s();"/>

RonPK

5:12 pm on Oct 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's not a good idea to let variables inside a function have the same name as the function; things may get confusing.

I cooked up this little script, using

setInterval()
and
clearInterval()
when it's ready.

var incw, w_end = 45, w = 35; 
function sl(){
var s=document.getElementById("input");
if (s.value=="Input") {
s.value="";
incw = setInterval("increaseWidth()", 500);
}
}
function increaseWidth() {
var inp = document.getElementById('input');
if (w < w_end) {
inp.style.width = w + 'px';
w++;
} else {
clearInterval(incw);
alert(w);
}
}

Fotiman

5:16 pm on Oct 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You might also look into the Yahoo UI Library. There is an animation utility [developer.yahoo.com] that will do this sort of transition for you.

birdbrain

5:33 pm on Oct 23, 2006 (gmt 0)



Hi there Jeremy_H,

and here is another example....


<!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">
<!--
#inp {
width:35px;
}
-->
</style>

<script type="text/javascript">
<!--
var w=35;
window.onload=function() {
document.getElementById('inp').onclick=function(){
s();
}
}
function s(){
w++;
if(w==200) {
clearTimeout(stretch);
return;
}
document.getElementById('inp').style.width=w+'px';
stretch=setTimeout('s()',50);
}
//-->
</script>

</head>
<body>

<form action="#">
<div>
<input type="text" name="q" value="Input" id="inp"/>
</div>
</form>

</body>
</html>

birdbrain

Jeremy_H

12:37 am on Nov 8, 2006 (gmt 0)

10+ Year Member



Thanks,

I have a lot of finessing to do, but you've opened me up to a better understanding of Intervals and Timeouts.