Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Colored Squares

Exercise 50 Average

Prerequisites for the exercise

  1. CSSOM — The style Property
  2. CSSOM Viewport
  3. All previous chapters

Objective

Create 5 squares shapes on a web page at random positions with random background colors of random length.

Description

Consider the following <div> element:

<div id="d1"><div>
#d1 {
   width: 50px;
   height: 50px;
   background-color: #aaa
}

It's square in shape, thanks to the identical width and height styles.

In this exercise, you ought to create 5 such square elements on a web page and position them randomly across the viewport.

The sizes of the squares must also be random. However, they must be in the range 50 - 100 (both inclusive).

The background color of each square element must also be randomly-chosen. Also note that each square must have an opacity of 0.8 so that it's easy to distinguish between two overlapping squares.

There is one thing to keep in mind while positioning the squares, i.e. each square must not extend the current dimensions of the viewport. In other words, all the squares must be completely visible within the bounds of the viewport.

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-50-Colored-Squares and put the .html solution files for this exercise within it.

Solution

The styles for the squares seem basic, so we'll start off by laying out them as follows, for the class .square:

.square {
   position: fixed;
   opacity: 0.8;
}

position: fixed is set because we want the squares to be fixed in the viewport. opacity: 0.8 is set as instructed in the description of the exercise (in order to distinguish between two overlapping squares).

As for the remaining styles — such as width, height, and background color — they'll all be applied to each square element node later on, as it's created, using its style property.

Time to turn to the scripting part.

Given so many random things, all of which require us to generate a random integer in a given range, let's start by creating a function to accomplish this. The function would return a random integer in a given range.

Let's call the function getIntegerRandom(start, end), where start denotes the starting point (inclusive) of the random integer's range while end denotes its ending point (inclusive as well).

Following is the definition of this function:

function getIntegerRandom(start, end) {
   return start + Math.floor(Math.random() * (end - start + 1))
}

Now if we call getIntegerRandom(0, 10), we'd get an integer in the range 0 - 10 (both inclusive). Simple?

With this done, let's now define a function that creates a square with a random background color, a random left and top position, and finally a random width and height. We'll call it getSquare().

The <div>'s creation is quite trivial — just call the createElement() method on the document object passing in the tag name of the element and then give it the .square class.

As for the generation of a random RGB color, we'll use another function, again defined manually. That is, getColorRandom(), defined as follows:

function getColorRandom() {
   return `rgb(${getIntegerRandom(0, 255)}, ${getIntegerRandom(0, 255)}, ${getIntegerRandom(0, 255)})`;
}

This function returns back a string of the form 'rgb(red, green, blue), where red, green, and blue are parameters of this CSS function filled with actual values. The return value is set this way so that it's pretty straightforward to use it for the backgroundColor style property on the given element.

Alright, given the getColorRandom() function, let's come back to the getSquare() function:

function getSquare() {
   var divElement = document.createElement('div');
   divElement.className = 'square';

   var width = getIntegerRandom(50, 100);
   divElement.style.width = divElement.style.height = width + 'px';

   divElement.style.backgroundColor = getColorRandom();

   // Keep the square within the width of the viewport.
   divElement.style.left = getIntegerRandom(0, innerWidth - width) + 'px';

   // Keep the square within the height of the viewport.
   divElement.style.top = getIntegerRandom(0, innerHeight - width) + 'px';
   return divElement;
}

Each statement here is pretty self-explanatory:

  • First, a <div> element is created and then given the 'square' class.
  • Next up, a random value is obtained and used as the width and height of the square element created.
  • After this, the background color of the square is set with the help of the getColorRandom() function.
  • Finally, the square is positioned on the viewport using the left and top CSS style properties and the getIntegerRandom() function.

The very last thing left now is to create 5 squares using this very getSquare() function in the underlying HTML page.

This is accomplished below:

function getIntegerRandom()  { /* ... */ }
function getColorRandom()  { /* ... */ }
function getSquare() { /* ... */ }

for (var i = 0; i < 5; i++) {
   document.body.appendChild(getSquare());
}

Live Example

And this completes our exercise.