[TIL] 211109

Lee Syong·2021년 11월 9일
0

TIL

목록 보기
83/204
post-thumbnail

📝 오늘 한 것

  1. 모멘텀 처음부터 다시 구현해보기

📚 배운 것

1. 모멘텀 구현

todo.js 파일 제외하고 나머지 구현

1) HTML & CSS

수정 필요함

🔎 HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>모멘텀 내 버전</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <form id="loginForm">
    <input maxLength="15" type="text" placeholder="안녕. 이름을 적어봐." required>
  </form>
  <div id="clock">00:00:00</div>
  <h1></h1>
  <form id="todoForm">
    <input type="text" placeholder="할일을 적어봐." required>
  </form>
  <div id="todos"></div>
  <div id="quotes">
    <span></span>
    <span></span>
  </div>
  <div id="weather">
    <span></span>
    <span></span>
  </div>

  <script src="js/greetings.js" defer></script>
  <script src="js/clock.js" defer></script>
  <script src="js/quotes.js" defer></script>
  <script src="js/background.js" defer></script>
  <script src="js/weather.js" defer></script>
</body>
</html>

🔎 CSS

.hidden {
  display: none;
}

2) greetings.js

  • onLoginFormSubmit 함수와 printGreeting 함수를 나눠 쓸 것
'use strict';

const loginForm = document.querySelector('#loginForm');
const loginInput = loginForm.querySelector('input');
const greetings = document.querySelector('h1');

const HIDDEN_CLASSNAME = 'hidden';
const USERNAME_key = 'username';

function onLoginFormSubmit(event) {
  event.preventDefault();
  const username = loginInput.value;
  printGreeting(username);
  loginForm.classList.add(HIDDEN_CLASSNAME);
  localStorage.setItem(USERNAME_key, username);
}

function printGreeting(name) {
  greetings.innerText = `안녕, ${name}! 반가워😁`;
  greetings.classList.remove(HIDDEN_CLASSNAME);
}

loginForm.addEventListener('submit', onLoginFormSubmit);

const localStorageName = localStorage.getItem(USERNAME_key);

if (localStorageName) {
  printGreeting(localStorageName);
  loginForm.classList.add(HIDDEN_CLASSNAME);
}

3) clock.js

  • 문자열.padStart(문자열 길이, 채울 문자)
'use strict';

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);

4) quotes.js

'user strict';

const quotes = [
  {
    quote: '생각하고 살지 않으면 사는 대로 생각하게 된다.',
    author: '폴 발레리'
  },

  {
    quote: '내가 생각했던 불행은 그다지 일어나지 않았다.',
    author: '몽테뉴'
  },

  {
    quote: '낭비한 시간에 대한 후회는 더 큰 시간 낭비이다.',
    author: '메이슨 쿨리'
  },

  {
    quote: '하루에 3시간을 걸으면 7년 후에는 지구를 한 바퀴 돌 수 있다.',
    author: '새뮤얼 존슨'
  },

  {
    quote: '행복은 소유에 있지 않고 존재에 있다.',
    author: '에리히 프롬'
  },

  {
    quote: '지금 이 인생을 다시 한 번 완전히 똑같이 살아도 좋다는 마음으로 살라.',
    author: '니체'
  }
];

function showQuotes() {
  const quote = document.querySelector('#quotes span:first-child');
  const author = document.querySelector('#quotes span:last-child');

  const randomIndex = Math.floor(Math.random() * quotes.length);
  quote.innerText = quotes[randomIndex].quote;
  author.innerText = quotes[randomIndex].author;
}

showQuotes();
setInterval(showQuotes, 1000);

5) background.js

  • 추후 유지·보수를 위해 randomIndex 부분에 숫자 3이라고 쓰는 대신, imgs.length라고 쓸 것

  • document.body.appendChild()에서 body를 빼먹으면 안된다

'use strict';

const imgs = ['0.jpg', '1.jpg', '2.jpg'];

const randomIndex = Math.floor(Math.random() * imgs.length);
const background = document.createElement('img');
background.setAttribute('src', `imgs/${imgs[randomIndex]}`);
document.body.appendChild(background);

6) weather.js

  • weather API를 사용하기 위해 url 변수를 만들 때 앞에 https://를 잊지 말고 붙여야 함
'use stirct';

function onGetOk(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const API_KEY = 'ec0fa8b152f1731f40ff6e8e9a1e9328';
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
  fetch(url).then(response => response.json()).then(data => {
    const weather = document.querySelector('#weather span:first-child');
    weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    const cityName = document.querySelector('#weather span:last-child');
    cityName.innerText = data.name;
  });
}

function onGetError() {
  alert('위치를 가져오는 데 실패했습니다.');
}

navigator.geolocation.getCurrentPosition(onGetOk, onGetError);

✨ 내일 할 것

  1. 모멘텀 마무리
profile
능동적으로 살자, 행복하게😁

0개의 댓글