- Greeting.js : 사용자로부터 입력을 받은 값을 Local Storage에 저장해 사용자를 기억합니다.
- Clock.js: 현재의 시간을 페이지에 나타냅니다.
- Quotes.js ,Background.js : 명언과 배경화면을 랜덤하게 화면에 띄워줍니다.
- Todo.js : 할 일을 User한테 입력받은 후, 바로 화면에 띄워줍니다. 또한, Greeting과 같이 Local Storage에 저장해두어 User가 다시 들어왔을 때 이전의 todo list를 띄워줍니다.
- Weather.js : navigator를 이용하여 현재 좌표를 받은 후, Open Weather API를 이용하여 현재의 위치의 날씨를 화면에 띄워줍니다.
지난 시간에는 Greeting.js에 대해 알아보았습니다. 이번에는 시간을 받아서 출력하는 Clock.js와 명언과 배경화면을 배경화면을 랜덤하게 띄워주는 Quotes.js,Background.js에 대해 설명한 후 배운점을 정리하겠습니다.
현재 시각을 띄워줍니다.
const clock = document.querySelector("#clock");
function getClock(){
const date = new Date();
const hours = String(date.getHours()).padStart(2,"0");
const minutes = String(date.getMinutes()).padStart(2,"0");;
const seconds = String(date.getSeconds()).padStart(2,"0");;
clock.innerText = `${hours}:${minutes}:${seconds} `;
}
getClock();
setInterval(getClock,1000);
자바스크립트에는 Date라는 기본적으로 제공하는 객체가 있다. 이 객체는 날짜와 시간을 제공하는 빌트인 객체이면서 생성자 함수입니다. 이 객체를 이용하여 손쉽게 현재의 시각을 받아올 수 있었다.
String(date.getHours()).padStart(2,"0");
'2자리를 고정으로 빈값이 있다면 앞에 0을 삽입하세요'라는 코드입니다.
따라서 위와 같이 실행되었습니다.
const date = new Date();
날짜와 시간을 제공받을 수 있는 기본 객체입니다.
.padStart(2,"0");
일정 조건에서 공백값을 앞에서 부터 0으로 채우게된다.
setInterval(getClock,1000);
일정 시간간격으로 getClock함수를 호출하게 됩니다. 1000ms(1초)에 한번씩 getClock() 함수를 호출합니다.
미리 저장되어진 명언 배열을 랜덤하게 추출하여 화면에 출력합니다.
const quotes =[ dict 형태로 저장. quotes: '', author:''];
const quote1 = document.querySelector("#quotes span:first-child");
const author1 = document.querySelector("#quotes span:last-child");
const todayQuote =quotes[Math.floor(Math.random() * quotes.length)];
quote1.innerText = todayQuote.quote;
author1.innerText = todayQuote.author;
위와 같은 형태로 새로고침 할때마다 새로운 quote들이 생성됩니다. JS에서 기본적으로 제공하는 Math 내장 객체를 사용했습니다.
Math.random() * quotes.length
Math.random은 0~1사이의 값을 랜덤하게 반환합니다. 이 때 quotes배열의 길이만큼 곱해주게 되면 '0~quotes의 길이' 사이의 랜덤한 값을 반환합니다.
Math.floor()
위 코드는 소수점을 버리는 버림으로 반환해줍니다. ex) 9.9 -> 9, 1.1 -> 1
const todayQuote =quotes[Math.floor(Math.random() * quotes.length)];
위와 같은 코드에서 todayQuote는 0~'배열의길이' 중 정수값을 랜덤으로 반환합니다.
Background 이미지를 랜덤하게 출력합니다.(새로고침 시)
const images =["image1.jpg","image2.jpg","image3.jpg"];
const chosenImages = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImages}`;
document.body.appendChild(bgImage);
출력하는 매커니즘은 Quotes와 동일합니다.
const bgImage = document.createElement("img");
createElement 로 'img' element를 생성합니다.
document.body.appendChild(bgImage);
body의 마지막에 img태그를 붙여줍니다.
appendChild 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다.