In this example we will create a header, and a list of options that will cause the header to be painted in different colors.
Create a web project: a folder with 3 files: 'index.html', 'main.js' and 'styles.css'.
Make sure the html page loads the other 2 files using <script>
and <link>
To the html add the following:
- A header with some text
- A list (use
<ul> and <li>
) with 4 items. Each item should have the name of a different color
Style the page nicely with CSS - freely.
Add javascript code, so that when each of the list items is clicked, it changes the background of the header. Each item should set the color of the header to a different color.
In this exercise we will practice using functions and parameters
Start with exercise 1, and build on top of it.
The function should get the name of the color as parameter, and place the proper class name on the header element.
Now make sure the Li elements do not each call a different function, but that they all call the same function with different parameter.
In this exercise we will practice:
document.createElement
element.addEventHandler
element.innerText
element.className
In our html file we have manually written 4 LI elements - one for each color. Now we would like to have more - perhaps 6 or 8 colors. Writing down each and every one of them is too much work. We would like to automatically create the LI items.
in your javascript file, create an array of colors:
var colors = ['red', 'green', 'blue', 'yellow', 'purple', 'brown'];
If your CSS contains different classes for different colors, make sure you also cover the new colors
Our goal is to remove the <li>
elements from the initial HTML and to build them from scratch in javascript. To start, lets create the function that inserts new LI elements.
In your javascript file, create a function that accepts a single parameter - the color (as string) - and adds the proper LI. Make sure to do the following:
- Set the inner text of the LI to the color
- Set the class name of the LI to the color
- Attach an event handler for 'click' so that when clicking the LI it will call the function that sets the header color, and will send it the correct color.
- Add the new LI to the UL element
In your HTML, respond to the 'load' event of the body element, and call a function in the Javascript file. The function should loop over the array of colors, and call the LI creation function each time with a different color