- 본 내용은 '노마드코더' 바닐라 JS 크롬 앱 만들기 강의를 보고 정리된 글입니다.
시계를 만들기 위해 시계가 출력될 공간(?)을 만든다.
class명은 css와 js에서 모두 사용하고자 할 경우에는 구분하여 'js-clock'으로 만들어 주는 것도 좋다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Momentum by juya</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="js-clock">
<h1>00:00</h1>
</div>
<script src="clock.js"></script>
</body>
</html>
시계를 출력할 요소를 찾아서 선택 후 변수에 할당한다.
시간 값을 가지고 오는 걸 실행할 함수를 생성한다.
new date() 내장 객체를 활용하여 시간, 분, 초를 각각 변수에 할당하여 출력한다.
const clockContainer = document.querySelector(".js-clock"), // querySelector는 element의 자식 요소를 찾는다.
clockTitle = clockContainer.querySelector("h1"); // clockContainer의 자식요소를 찾는다.
function getTime() {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
} // 삼항 조건 연산자 활용
// 시간, 분, 초가 한자리 수가 되면 01이 아닌 1만 나오기 때문에 삼항 조건 연산자를 활용하여 보기 좋게 변경한다.
function init() {
getTime();
setInterval(getTime, 1000); // setinterval (함수, 반복시간)
}
init();
setInterval
: 함수를 원하는 조건으로 반복innerText
: html 태그의 내부 Textf를 가지고 올때 사용new Date()
: Date 객체를 생성하고, Date 객체는 날짜를 얻는 함수를 가지고 있는 객체로 우선 이해하자.삼항 조건 연산자
: (조건 ? 참 : 거짓)