X hits on this document

Word document

JavaScript Tutorial: bouncing ball - page 6 / 7





6 / 7

Add the script tags:



In between the script tags, add the getObj function shown above.  Include the following variables:

var ballobj;

var tid;

var xa = 20;

var ya = 40;

var currentx = 100;

var currenty = 200;

The xa and ya values are the incremental horizontal and vertical changes.  In mathematics, x is associated with the horizontal dimension and y with the vertical dimension, but there is nothing special about these names.  The only thing that matters is how they are used in your code. The values of 20 and 40 are arbitrary.  Change them to see what different values do.  

Make sure the values of the currentx and currenty variables match the values in the style specification for the div with id #ball.  

You will now write 3 functions: start, stop and move, all within the script element (after the <script> and before the </script>).   The start and stop functions use the setInterval and clearInterval functions in the same manner as in the slide show.

function start() {

ballobj = new getObj("ball");

tid = setInterval("move(xa,ya);",300);


function stop() {


xa = -xa;

ya = -ya;


The reversal of the xa and ya amounts is just to supply some interest to the application. You can change this to have stopping have no effect or you can  swap the two values or do anything you like.  To swap the values, you need to make use of an extra variable:

holder = xa;

xa = ya;

ya = holder;

Document info
Document views26
Page views26
Page last viewedSat Jan 21 09:19:58 UTC 2017