Working with the Date API

Today:

Night / day site

The goal is to make a site that changes based on whether it’s day or night.

Let’s start by making a button

<div class='pagecontent'>
  <button>click me</button>
</div>

If we click the button, it doesn’t yet do anything. Let’s give some instruction.

Add a color class.

.black {
  background-color: black;
}

Now let’s hook up our Javascript:

function displayTime(){
  let currentTime = new Date();
  let hours currentTime.getHours();
  let minutes = currentTime.getMinutes();
  let seconds = currentTime.getSeconds();
}

Let’s display this info

//grab our clock element
let clockDiv = document.getElementById('clock');

//set the text in the div

clockDiv.innerText = hours + ":" + minutes + ":" + seconds;

So our Javascript now looks like this:

$(document).ready( function() {

  function displayTime() {
    let currentTime = new Date();
    let hours = currentTime.getHours();
    let minutes = currentTime.getMinutes();
    let seconds = currentTime.getSeconds();

    // This gets a "handle" to the clock div in our HTML
    let clockDiv = document.getElementById('clock');

    // Then we set the text inside the clock div 
    // to the hours, minutes, and seconds of the current time
    clockDiv.innerText = hours + ":" + minutes + ":" + seconds;
  }

  // This runs the displayTime function the first time
  displayTime();

});

Now we’ll make it visible.

<body>
   <div id='clock'></div>
</body>

We should now see the clock.

Let’s make it look good.

body {
    background-color: #80d4ea;
}

#clock {
    height: 100px;
    width: 800px;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    padding-top: 70px;
    font-family: courier, monospace;
    text-align: center;
    color: white;
    font-size: 100px;
}

So far, the clock is just presenting the time at page load. But then nothing after that. Let’s make it advance every second.

setInterval(displayTime, 1000);

Challenge: How to fix the display

  1. Digits 1-9 just show one digit. How do we fix that?
  2. How do we show AM or PM?

Web-based IDE and server: Glitch.com

Glitch

Assignment - Build a Better Clock

Examples of other alternative clocks

For this assignment, you are welcome to stick with and build off this counting digital clock approach. The following are clocks that count in a more ‘analog’ style.

Homework:

Build your own custom clock. Due in three weeks.

This is a project to use the Date() API in the browser to flex your muscle with HTML, CSS and JS to build a web application. You can choose what you want to make with this framework, but make it unique. Show us your creative take.

Examples:

This project is due in 3 weeks, on the 27th.

This project will be evaluated by: