Not logged in. Login

Exercise 11

In this exercise, we will experiment a little more with for and if in JavaScript.

A Grid

Create an HTML page with a text input, a button, and container for a Raphaël paper object. We will have the user enter a number in the form and click the button, and then draw an n×n grid of squares.

If the user enters 8 in the text input and clicks the button, you should draw eight rows and columns of little squares. To do this, you will need two for loops nested inside each other like this:

for ( row=1; ... ) {
  for ( col=1; ... ) {
    ...
  }
}

In the (inner-most) loop body, draw a little square on the paper with an x and y value calculated from the loop counters so the squares end up in a grid pattern.

Your page will look something like this (depending on the number the user enters, obviously). Don't worry about the coloured boxes yet: that is the next part.

E11-screen/view

Adding Conditions

We want some of the squares to have a fill colour: the ones with row + col larger than the number the user entered.

Add an if inside the for loop to check a condition and set the 'fill' attribute (of the rectangle you just drew) if it's true.

We also want to restrict the user from entering number too large: we can't sensibly draw a 100×100 grid. Add a condition so that nothing will be drawn for numbers more than 15. (You can display an error for larger numbers or just do nothing.)

Style

Create a stylesheet for your page. At least make the <input> a reasonable size for what we expect to be entered (by setting its width).

Add other styles as you like to make it look less generic.

Submitting

Upload the files to the course web server, as you have before and make sure everything is working. You may want to create a folder exercise11. Submit the URL of your HTML page to the CourSys activity Exercise 11.

Updated Sat Aug. 24 2019, 11:27 by ggbaker.