Jump to content

moving div using 'while' and 'setTimeout'


newrehmi

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!!!!

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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...