Jump to content

moving div using 'while' and 'setTimeout'


Recommended Posts

hello guys!!I am trying to make a div moving once I click the button. It must keep on moving on every 1 second until it reach 1000px of left value for the div style. Here is my code:

<html><head><style type="text/css">#help {width:100px;height:100px;background:red;position:absolute;}</style></head><body><script type="text/javascript">var pixel = 0function move(){while(pixel <= 1000){document.getElementById("help").style.left = pixelpixel = pixel + 100setTimeout("move()",1000)}}</script><div id="help"></div></br></br></br></br></br><input type="button" value="move it" onclick=move() /></body></html>

But, none of my code is working... =\ Can anyone give some briefing about what is wrong with my script? and what should I do to make it working? (any tips or magic word should be working on me!! >.<)Later, I am going to learn on how to make a moving div, so that I can move it smoothly by altering the timeout value.Thank you sooo much!! and sorry again for this noob question =_+ThankS!!!!

Edited by newrehmi
Link to comment
Share on other sites

You do not want to put setTimeout inside a while conditional in this way. In addition to calling move every second, the while loop calls move with every iteration. To all intents and purposes, an iteration happens at the speed of light. This is why the div moves to the right side instantaneously.The simple fix is to change while to if.When you add a doctype to this document (all HTML documents need a good doctype) you will find that this does not work in all browsers:<input type="button" value="move it" onclick=move() />Change it to this:<input type="button" value="move it" onclick="move()" />Notice the quotation marks.

Edited by Deirdre's Dad
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...