First Step

Simple Realtie Clock

실시간 현재 시간을 알려줍니다.

html: index.html

<html lang="ko">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css" />
    <title>Clock</title>
  </head>
  <body>
    <main class="container">
      <h1 id="title">00:00</h1>
    </main>
    <script src="clock.js"></script>
  </body>
</html>

css: style.css

main {
  width: 100%;
  height: 100vh;
  background-color: gainsboro;
  display: flex;
  justify-content: center;
  align-items: center;
}

#title {
  font-size: 180px;
}

javascript: clock.js

공부할 내장 함수: Date()

공부할 ES6 내용: 내장함수, 템플릿 리터럴, 삼항연산자 (조건 ? 참일 때 실행 : 거짓일 때 실행)

var clockContainer = document.querySelector('main');
var clockTitle = clockContainer.querySelector('#title');

function getTime() {
  var date = new Date(); // Date class
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  if (seconds > 50) {
    clockTitle.style.color = 'red';
  } else {
    clockTitle.style.color = 'black';
  }
  clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` :seconds}`;
}

function init() {
  getTime();
  setInterval(getTime, 1000);
}

init();