JS로 Momentum Clone하기! - 2

배준현·2021년 9월 3일
0

JS로 Momentum Clone

목록 보기
2/3
post-thumbnail

💥 Javascript를 이용하여 웹 페이지 구현해보자

Nomad Coder님의 'Vanilla JS로 크롬 앱 만들기'를 따라가며 제가 배운 것들을 정리하는 포스트입니다.

'바닐라 JS -> 관련 프레임워크 -> 백엔드' 로 빠르게 웹 개발과정을 돌아보는 과정의 시작입니다.

글 솜씨가 아주 부족합니다..

각 기능별로 여러개의 javascript 파일로 나누어 구현합니다.

  1. Greeting.js : 사용자로부터 입력을 받은 값을 Local Storage에 저장해 사용자를 기억합니다.
  2. Clock.js: 현재의 시간을 페이지에 나타냅니다.
  3. Quotes.js ,Background.js : 명언과 배경화면을 랜덤하게 화면에 띄워줍니다.
  4. Todo.js : 할 일을 User한테 입력받은 후, 바로 화면에 띄워줍니다. 또한, Greeting과 같이 Local Storage에 저장해두어 User가 다시 들어왔을 때 이전의 todo list를 띄워줍니다.
  5. Weather.js : navigator를 이용하여 현재 좌표를 받은 후, Open Weather API를 이용하여 현재의 위치의 날씨를 화면에 띄워줍니다.

지난 시간에는 Greeting.js에 대해 알아보았습니다. 이번에는 시간을 받아서 출력하는 Clock.js와 명언과 배경화면을 배경화면을 랜덤하게 띄워주는 Quotes.js,Background.js에 대해 설명한 후 배운점을 정리하겠습니다.

1. Clock.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라는 기본적으로 제공하는 객체가 있다. 이 객체는 날짜와 시간을 제공하는 빌트인 객체이면서 생성자 함수입니다. 이 객체를 이용하여 손쉽게 현재의 시각을 받아올 수 있었다.

💻실행

처음 실행했을때는 위와 같은 형태로 출력되었습니다. 근데 '2'와 같이 출력하기 보다는 '02'와 같이 출력하고 싶었습니다. String에서 제공하는 Padstart 속성을 이용하여 한자리수일때는 앞에 0을 삽입시켜주는 속성을 추가해주었습니다.
 String(date.getHours()).padStart(2,"0");

'2자리를 고정으로 빈값이 있다면 앞에 0을 삽입하세요'라는 코드입니다.

따라서 위와 같이 실행되었습니다.

✨ 배운점 1 : Date 객체

const date = new Date();

날짜와 시간을 제공받을 수 있는 기본 객체입니다.

✨ 배운점 2 : padstart 속성

.padStart(2,"0");

일정 조건에서 공백값을 앞에서 부터 0으로 채우게된다.

✨ 배운점 3 : setInterval()

setInterval(getClock,1000);

일정 시간간격으로 getClock함수를 호출하게 됩니다. 1000ms(1초)에 한번씩 getClock() 함수를 호출합니다.

2. Quotes.js

미리 저장되어진 명언 배열을 랜덤하게 추출하여 화면에 출력합니다.

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 내장 객체를 사용했습니다.

✨ 배운점 1 : Math.random

Math.random() * quotes.length

Math.random은 0~1사이의 값을 랜덤하게 반환합니다. 이 때 quotes배열의 길이만큼 곱해주게 되면 '0~quotes의 길이' 사이의 랜덤한 값을 반환합니다.

✨ 배운점 2 : Math.floor

Math.floor()

위 코드는 소수점을 버리는 버림으로 반환해줍니다. ex) 9.9 -> 9, 1.1 -> 1

const todayQuote =quotes[Math.floor(Math.random() * quotes.length)];               

위와 같은 코드에서 todayQuote는 0~'배열의길이' 중 정수값을 랜덤으로 반환합니다.

3. Background.js

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와 동일합니다.

✨ 배운점 1 : createElement()

const bgImage = document.createElement("img");

createElement 로 'img' element를 생성합니다.

✨ 배운점 2 : appendChild()

document.body.appendChild(bgImage);

body의 마지막에 img태그를 붙여줍니다.

appendChild 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다.

다음시간에는 가장 어려웠던 Todo와 Weather을 구현했던 것을 회고하겠습니다.

profile
취업어케하죠

0개의 댓글