This website is an example of how JavaScript can be used to manipulate the DOM. Every second, a new shape is randomly generated and added to the page.
For this guided practice, you will be implementing new features by modifying index.html and index.js. You will not need to make any changes to index.css, but you should take a look at it to see the class names that will be applied.
The answers can be viewed directly below the respective prompt. The solution branch contains the final code.
-
Currently the shapes can only be red, green, or blue. Update the code so that the shapes can also be orange, yellow, or purple.
Show Answer
const colors = ["red", "green", "blue", "orange", "yellow", "purple"];
-
The website will continue to generate shapes forever. Update
addShapeto stop the interval after the max number of shapes has been reached.Show Answer
if (shapes.length >= maxShapes) { clearInterval(addShapeIntervalId); }
-
Only small shapes are being generated right now, but we have support for other sizes as well! Update
addShapeso that the new shape will be a random size.Show Answer
const size = sizes[Math.floor(Math.random() * sizes.length)];
-
Add a new list in the HTML for circles, and update the JS so that circles are also generated. The website should now generate both a square and a circle every second. The circles do not count toward the max number of shapes.
Show Answer
<ul id="circles"></ul>
function render() { // ... const circleList = document.querySelector("#circles"); const circleElements = shapes.map((shape) => { const circleElement = document.createElement("li"); circleElement.classList.add(shape.color, shape.size); return circleElement; }); circleList.replaceChildren(...circleElements); }
If you're done early, try to implement one or more of the following features:
- Circles now count toward the max number of shapes.
- Add support for an extra large size of shapes.
- Add an announcement to the page when the max number of shapes has been reached.
- Create a counter on the page that shows how many shapes have been generated so far.
- The textContent property will be useful here!