Exercise 1
Visit sleepyti.me and click on the zzz
button; notice the wake up hours are color coded. Create the same effect in our app (use the same colors).
Solution
We can wrap each wake up hour in a <span></span>
tag with a unique ID for each cycle:
<p id="hours">
<span id="cycle-1">11:44 PM</span> or
<span id="cycle-2">1:14 AM</span> or
<span id="cycle-3">2:44 AM</span> or
<span id="cycle-4">4:14 AM</span> or
<span id="cycle-5">5:44 AM</span> or
<span id="cycle-6">7:14 AM</span>
</p>
The
<span>
tag is much like the<div>
element, but<div>
is a block-level element and<span>
is an inline element.
We can then update our style.css
file to assign the desired colors to each "cycle":
#cycle-1 {
color: rgb(168, 39, 254);
}
#cycle-2 {
color: rgb(154, 3, 254);
}
#cycle-3 {
color: rgb(150, 105, 254);
}
#cycle-4 {
color: rgb(140, 140, 255);
}
#cycle-5 {
color: rgb(187, 187, 255);
}
#cycle-6 {
color: rgb(143, 254, 221);
}
- Note CSS ID selector starts with
#
- Moreover, notice we can specify colors by their
rgb
values.
I picked up the values by inspecting the output on sleepyti.me.
To generate this output programmatically, we need to update our JavaScript code:
function handleOnClickEvent() {
let output = document.querySelector('.output');
output.style.display = 'block';
let now = Date.now();
let minute = 60 * 1000; // miliseconds
let hours = document.getElementById('hours');
hours.innerText = ""; // cleanup exisitng content
now += 14 * minute; // fall sleep
// compute sleep cycles
for (let c = 1; c <= 6; c++) {
now += 90 * minute;
let cycle = new Date(now);
let span = document.createElement("span");
span.id = "cycle-" + c;
span.innerText = cycle.toLocaleTimeString();
hours.appendChild(span);
if (c < 6) {
let or = document.createTextNode(" or ");
hours.appendChild(or);
}
}
}
- The createElement() method creates an HTML Element Node with the specified name.
- The createTextNode() method creates a Text Node with the specified text.
- The appendChild() method appends a node as the last child of a node.