The Mysterious Box
This is
a small exercise using JavaScript with some simple styling.
Create a page which contains an empty box with some controls, like this:
The controls, as you see, are entry boxes for the height and width, and
a Set button which applies those to the box. The
Random Color button changes the background of the box to a new color
chosen at random. The size dimensions are in pixels. If I enter
a new height of 200 and width of 600 and press set, I get:
Then a press of the Random Color button might give me:
The box is just an empty
div, initially gray, 50 pixels high and 100 pixels wide.
The entry inputs are simply HTML input tags, type text. The buttons are
made with the HTML button tag.
Each button has an onClick binding to some JavaScript code which performs
the required function.
- When the set button is pressed, change the height and width of
the box according to the input values, then clear the input boxes.
Units are pixels.
Set the dimension only when there is a valid integer in the input box.
If only one dimension is valid, change only that one. (Of course, if
both entries are empty, the box size is not changed.)
- When the Random Color button is pressed, choose a new color at
random. Choose new red, green and blue values at random from the
full range, 0-255, and set the box background to that color.
The callbacks adjust the style settings on the
div box to have their effect.
When the setting callback runs, it needs to check the entered
sizes to see if they're valid. I just converted them to integer with
Number.parseInt, and checked that the value was not
NaN and was positive. Of course, it doesn't actually need to
be converted to an integer, so string operation checks should work fine
(or maybe better).
For random numbers, JavaScript has Math.random(). I ran it
three times and did the arithmetic (using also Math.floor) to
choose three component numbers, and built a CSS-style RGB string, like
rgb(50,78,12), and assigned that to the
backgroundColor style.
My solution is all in one file, but you may break it up as you see fit.
Style it as you like; doesn't have to look like mine (you may even
attempt pretty), but you do need to have the listed parts in some
reasonable presentation
After you post your page on Sandbox, make sure you can view it online,
then send me the page URL through
this form.