X hits on this document

Word document

JavaScript Tutorial: bouncing ball - page 7 / 7





7 / 7

Place the following code in the body of the HTML document.

<a href="javascript:start();">Start </a>&nbsp;

<a href="javascript:stop()">Stop </a>

What remains is to write the move function.  We propose doing this in two stages.  The code

function move(dx, dy) {

  currentx += dx;

  currenty += dy;

  ballobj.style.top = currenty;

  ballobj.style.left = currentx;


moves the ball by first incrementing the variables holding the current horizontal and vertical position and then storing those values in the appropriate properties of ballobj.  Because ballobj has been created as it has been, this has the effect of moving the ball.

Get this working!  If you have problems, first look over your coding.  Match up parentheses, curly brackets, pointy brackets, opening tags and closing tags. Check spelling. See if the <a> tags are invoking the start function by putting the lines

alert("in start "+"currentx is "+currentx);

alert(" currenty is "+currenty);

as the first line in the start function.  Do the same for the move function, perhaps checking on the values of dx and dy.  Change the timing value to be longer (say 2000) so you have time to hit refresh to stop the action.

Assuming you do get this working, you will notice that the code does not check hitting the walls.  Remember that there are no walls! The following code checks against virtual walls located at the top and on the left and at 250 units to the left and 250 units from the top.  Place the code in the move function the code you have already written.

if (currentx >= 250) {

   xa = -xa; }

if (currentx <=0) {

   xa = -xa;}

if (currenty >=250) {

   ya = -ya; }

if (currenty <=0) {

   ya = -ya; }

You can experiment with changing these values.

Document info
Document views25
Page views25
Page last viewedFri Jan 20 08:52:06 UTC 2017