PDA

View Full Version : Restarting a for-loop stopped by "break" -- or some alternative?



sepdet
10-10-2007, 04:35 AM
Hello! Brand new noob here attempting my very first Javascript.

Someone told me to put this into the Location Bar while viewing a webpage with some graphics on it, and the effect intrigued me:

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5); void(0)

So I decided to try and put a button on an existing web page that would trigger the script. This meant figuring out how to define variables and invoke functions in a full-fledged script. After much head-scratching, I got it to work -- here (http://www.istad.org/mc/test.html) is the link to my test-page with a demo -- (but see below). Here is the script I wrote:


<HTML><BODY>
<form>
<input type="button" value="click me!" onClick="surprise()">
</form>
<P>
<!-- (some random .gifs) -->
<P>
<input type="button" value="ack, stop!" onClick="stop()">

<script language="JavaScript">
<!--
var running = true;
var R=0; var i;
var x1=.1; var y1=.05;
var x2=.25; var y2=.24; var x3=1.6; var y3=.24;
var x4=300; var y4=200; var x5=300; var y5=200;
var DI=document.images;
var DIL=DI.length;
var DIS;

function A()
{

for(i=0; i<DIL; i++) {
if (running) {
var DIS=DI[ i ].style;
DIS.position="absolute";
DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5;
DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5
} else {

break;}
}
R++
}

function surprise()
{
setInterval('A()',5)
}

function stop()
{
running = false;
}
// -->
</script>
</body></html>


As you see, I figured out how to create a "stop" button.

Two problems are still defeating me.

1) after clicking "stop" the "start" button ("click me!") no longer works. That's silly. It should still work. I tried putting

running=true;

right before the "break" inside the "else" curly quotes, but then the for loop never stops.

So how can I get the for loop to stop when someone clicks "stop" but restart if someone clicks on the "click me" button? I have a feeling I should be using "while" instead but I can't quite work out the syntax.

(Eventually, I want to include a stop sign graphic among the graphics, and make the graphic a link... but one step at a time.)


2) Even more silly, after hitting "stop" I'd like all the graphics to go back to their places. I tried including

DIS.position="relative";

right before the break; inside the curly quotes, but that had no effect. I suppose I probably to reset their coordinates manually?



This is all very silly, but I've learned a lot in a few hours just by poking at it. Anyone feel like giving a newbie a leg up? :rolleyes: