[Nomad coders - 바닐라 JS로 크롬 앱 만들기] 실습

임유정·2023년 5월 25일
0

⏰ CLOCK

현재시간 출력 코드 (Before)

const clock = document.querySelector("#clock");

function getClock() {
  const date = new Date();
  clock.innerText = (`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`)
}

getClock();
setInterval(getClock, 1000); //1초마다 갱신

현재 시간을 잘 나타내고 있지만,
"9" 일의 자리로 표현되는게 아니라 두 자리로 "00"표현되고 싶다.

HOW?

padStart()를 사용해서 padding을 추가해달라고 자바스크립트로 요청하면된다!

"1".padStart(2,"0") //두 자리수로 보이게하고, 패딩스타트를 0으로 채운다.
'01'

현재 시간 가져오기 최종 코드 (Result)

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);
  • "string"은 "String" 으로 대문자로 시작해야 제대로 인식됨
  • number를 string으로 바꾸는 방법은 String() 안에 감싸는 방법이 있다.
  • 뒤에서 추가하고 싶을 때는 padEnd를 사용하면 된다.

궁금증 : 근데 왜 Date라는 객체를 바로 안쓰고 new로 새로운 객체를 만드는가?

해결 : new Date() 객체를 date 변수에 할당함으로써, 이후 코드에서 getHours(), getMinutes(), 그리고 getSeconds()와 같은 Date 객체의 여러 속성과 메소드에 접근할 수 있다.
따라서, new Date()는 현재 시간을 나타내는 새로운 Date 객체를 생성하여, 해당 시간의 시, 분, 초를 가져올 수 있도록 하는 데 필요하다.
const 지정할변수 = new 생성자()
뭐.. 태생적으로 이런 식으로 생겨먹은 애들이라고 하니 더 이상 근본적으로 파고들어봤자 이해못할거 같아서 '그런갑다'하고 받아들였습니다

📑 QUOTES AND 🖼️ BACKGROUND

배운것

Math.floor는 소수점을 버리는 것(버림),
Math.ceil은 소수점을 올리는 것(올림),
Math.round는 소수점을 반올림/반내림 하는 것

명언과 명언을 만든 작가의 텍스트를 배열로 받아 랜덤으로 뿌려준다.

const quotes = [{
    quote: 'I never dreamed about success, I worked for it',
    author: 'Estee Lauder'
  },
  {
    quote: 'Do not try to be original, just try to be good.',
    author: 'Paul Rand'
  },
  {
    quote: 'Do not be afraid to give up the good to go for the great',
    author: 'John D. Rockefeller'
  },
  {
    quote: 'If you cannot fly then run. If you cannot run, then walk. And if you cannot walk, then crawl, but whatever you do, you have to keep moving forward.',
    author: 'Martin Luther King Jr.'
  },
  {
    quote: 'Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.',
    author: 'Thomas Edison'
  },
  {
    quote: 'The fastest way to change yourself is to hang out with people who are already the way you want to be',
    author: 'REid Hoffman'
  },
  {
    quote: 'Money is like gasoline during a road trip. You do not want to run out of gas on your trip, but you are not doing a tour of gas stations',
    author: 'Tim O Reilly'
  },
  {
    quote: 'Some people dream of success, while other people get up every morning and make it happen',
    author: 'Wayne Huizenga'
  },
  {
    quote: 'The only thing worse than starting something and falling.. is not starting something',
    author: 'SEth Godin'
  },
  {
    quote: 'If you really want to do something, you will find a way. If you do not, you will find an excuse.',
    author: 'Jim Rohn'
  },
];

const quote = document.querySelector("#quoteMessage");
const author = document.querySelector("#author");


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

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

백그라운드 이미지 넣기

const images = [
  "testImg1.jpg",
  "testImg2.jpg",
  "testImg3.jpg"
];

const chosenImg = images[Math.floor(Math.random() * images.length)];
const backgroundImg = document.createElement("img");

backgroundImg.src = `img/${chosenImg}`
document.body.appendChild(backgroundImg);
  • 알게된점
    appendChild()
    // 함수 안의 경로에 정의한 값을 가장 뒤에서 기입함
    prependChild()
    // 반대로 앞에서 기입

🏷️ TO DO LIST

const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input");
const toDoList = document.getElementById("todo-list");
const toDos = [];

function saveToDos(){
  localStorage.setItem("toDos", JSON.stringify(toDos));
}

function deleteToDo(event){
  const li = event.target.parentElement;
  li.remove();
}

function paintToDo(newTodo){
  const list = document.createElement("li");
  const todoContent = document.createElement("span");
  const button = document.createElement("button");
  button.innerText = "❌";
  button.addEventListener("click", deleteToDo);
  list.appendChild(todoContent);
  list.appendChild(button);
  todoContent.innerText = newTodo;
  toDoList.appendChild(list);
}

function handleTodoSubmit(event) {
  event.preventDefault();
  const newTodo = toDoInput.value;
  toDoInput.value = "";
  paintToDo(newTodo);
  toDos.push(newTodo);
  saveToDos();
}

toDoForm.addEventListener("submit", handleTodoSubmit);

알게된점

  • STRINGIFY = 변수 등을 문자열로 바꿈,PARSE = 문자열을 JSON으로 바꿈

    1. 이전 영상에서 우리는 추가와 삭제가 가능한 멋진 todo-list를 화면에 구현했다..!
      하지만 새로고침을 하거나 이용자가 누구인가와 관계없이 똑같은 todo-list가 나온다면 우리는 todo-list를 그 때마다 계속해서 작성해야할 것이다. 만약 todo-list를 1,000개 작성했는데 단숨에 날라간다면...? 그건 어딘가 부족한 todo-list 일 거다. 그래서 우린 todo-list에 나타낸 텍스트를 저장하는 기능이 필요하다.
    1. todo - list의 배열 생성
      1) const toDos = [ ]; // toDo에 들어오는 텍스트를 배열로 묶어 보관하기 위해 빈 array를 생성해준다.
    1. 저장 기능을 함수를 정의한다.
      1) 아직 기능을 하진 않지만 우리는 화면에 나타낸 텍스트를 저장할 것이기 때문에 대충 그러한 기능을 하는 함수가 있다고 치고 빈 함수
      function saveToDos( ) {
      };
      를 생성한다.
      2) 앞에서 만들었던 함수 handleToDosubmut( ); 의 맨 마지막에 저장 기능을 실행할 saveToDos(); 넣어두고 다음에서 기능을 구현한다.
    1. todo - list를 저장하는 기능을 수행하는 함수 설정
      1) function saveToDos( ) { localStorage.setItem("todos",toDos); } 에 "todos"라는 이름의 카테고리로 저장한다.
      2) 하지만 이렇게 저장하게 되면 직접 localStorage 에서 확인해봤을 때 값들이 array안에서
      string의 형태가 아닌 상태로 저장된다.
      예) key: todos value: a,b,c
      3) 하지만 우리는 값들을 string의 형태로 toDos라는 array에 집어넣고 싶기 때문에 니꼬가 알려준 JSON.stringify() 라는 객체를 사용한다. 이 도구는 우리가 대입한 값을 알아서 string의 형태로 바꿔줄 것이다.
      예) key: todos value: ["a", "b", "c"]

forEach();

toDoForm.addEventListener("submit", handleTodoSubmit);

function sayHello(){
  console.log("say hello");
}
const savedToDos = localStorage.getItem(TODOS_KEY);

if(savedToDos !== null){
  const paresdToDos = JSON.parse(savedToDos);
  console.log(paresdToDos);
  paresdToDos.forEach(sayHello);
}
  1. To-Do-List 작성시 localStorage 에 저장이 된다.
  2. 근데 저장이 될때 string data type 으로 저장이 됨. (예: "[a,b,c,d,e]")
  3. 그래서 JSON.parse()를 통해 string data type을 object로 바꾼거다. 근데 이 Object는 Array 같이 바뀌었고. 즉 index를 통해 value를 access할 수 있다.
    예: "[a,b,c,d]" (string) => a, b, c, d;
    array[0] = a; array[1] = b; array[2] = c; array[3] = d
  4. array 형태가 된 값을 parsedToDos 라는 const variable 에다가 넣는다.
  5. 이 상태에서 parsedToDos 는 array 형태라고 가정했을때 .foreach() 라는 function 을 사용할수 있는데 이건 mdn 웹사이트 가면 나오지만 그냥 단순히 array 에 들어있는 모든 값을 iterate (순찰(?)) 할수 있는 function 이다.
  6. 즉 index 0 부터 마지막 index 까지 한 바퀴 도는건데 돌면서 그 값들을 item 라는 곳 또는 element에 (이름은 정하기 나름) 저장이 되는거다.

WEATHER

function onGeoOk(position){
  const lat = position.coords.latitude; //위도
  const lng = position.coords.longitude; //경도
  console.log("You live it", lat, lng);
}
function onGeoError(){
  alert("Can't find you, No weather for you")
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
  1. navigator 함수를 이용해 사용자의 위치를 알아내는 코드 작성.

navigator.geolocation.getCurrentPosition ( ) 라는 코드를 작성해준다.
이때 getCurrentPosition 은 2개의 argument가 필요하다. 앞쪽에는 모든 게 잘 됐을 때 실행될 함수인 onGeoOk 함수를, 뒤에는 실패했을 때 실행될 함수인 onGeoError 함수를 입력한다.

  1. onGeoError() 함수가 실행될 때 :
    에러가 났다는 것을 사용자에게 알려주기 위해서
    alert("Can't find you. No weather for you."); 를 해준다.

  2. onGeoOk 함수가 실행될 때:
    function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    console.log("You live in", lat, lng);
    }

자바스크립트가 position으로 user의 위치를 전달해준다.
position은 object 이고 위도와 경도 값이 들어있다. positon.coords.latitude와
position.coords.longitude 를 변수에 저장하고 console.log를 해서 사용자에게 보여준다.

지리적 위치: getCurrentPosition() 메서드를 사용해서 user의 위치와 장소 이름을 확인 할 수 있다.

날씨 API 사용하기

사용할 API는 유명한 OpenWeatherMap API를 사용한다.

https://openweathermap.org/api
API Doc을 클릭하여 문서를 보면 된다.

문서를 보면 알 수 있다시피 여기서 제공해주는 것은 우리 지역의 현재 날씨 등을 제공해주고 있다.

문서의 밑에 부분을 보면 어떻게 API를 call 할 수 있는지가 설명되어있다.
Geolocation.getCurrentPosition()
장치의 현재 위치를 가져오는 메소드이다.
기본 문법

navigator.geolocation.getCurrentPosition(success[, error[, [options]])
success 함수는 GeolocationPosition 객체를 유일한 매개변수로 받는 콜백 함수이다.

Weather API 이용하기
https://openweathermap.org/
계정 생성 > Current Weather Data > API doc > By geographic coordinates

function example(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`
    console.log(url)
    
    fetch코드...
}

Geolocation API 메소드
Method 설명
getCurrentPosition() 사용자의 현재 위치를 가져옴.
watchPosition() 사용자의 현재 위치를 가져오고 나서, 사용자의 움직임에 따라 지속적으로 위치 정보를 갱신함.
clearWatch() watchPosition() 메소드의 실행을 중지함.

getCurrentPosition() 메소드의 반환 값
속성 반환값
coords.latitude 소수로 표현된 위도 값
coords.longitude 소수로 표현된 경도 값
coords.accuracy 위도 값과 경도 값의 정확도
coords.altitude 평균 해수면을 기준으로 하는 고도 값(해발)
coords.altitudeAccuracy 고도 값의 정확도
coords.heading 북쪽을 기준으로 현재 진행 방향에 대한 시계방향으로의 각도 값(˚)
coords.speed 초당 이동한 미터 수를 나타내는 속도 값(초속)
timestamp 위치 정보를 가져온 시간을 나타냄.

profile
console.log(youjung(🌼 , 🍣)); // true

0개의 댓글