To Do List 사이트 만들기

2021. 8. 16. 14:08웹 코딩/개인 프로젝트

To Do List

 

To Do List 사이트 만들기

구현 기능

  • 현재 시간
  • 날씨
  • 배경화면, 명언 무작위로 나타내기
  • To Do List 작성
  • 로그인 기능

 

현재 시간

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

 

function getClock() {

  const date = new Date();

  clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;

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

 

1초 마다 새로고침하여 현재 시간을 매 초마다 보여주고 초 단위를 십의 자리로 표시한다.

 

 

날씨 기능

const weather = document.querySelector("#weather span:first-child");

const city = document.querySelector("#weather span:last-child");

const API_KEY = "b859cfa8e1f1cf7641cbcc41a3724bb7";

 

function onGeoOk(position) {

  const lat = position.coords.latitude;

  const lng = position.coords.longitude;

  console.log("You live in"latlng);

  const lon = position.coords.longitude;

  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=> {

      city.innerText = data.name;

      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;

    });

}

function onGeoError() {

  alert("Can't find you. No weather for you.");

}

navigator.geolocation.getCurrentPosition(onGeoOkonGeoError);

  

오픈 API에서 날씨 데이터를 받아 실시간으로 날씨의 정보를 보여준다.

 

 

 

명언 10개 무작위로 나타내기

const quotes = [

    {

      quote: "때가 되면 마땅히 스스로 공부에 힘써야 하며 세월은 사람을 기다리지 않는다.",

      author: "도연명",

    },

    {

      quote: "목적을 이루기 위해서 오랜 인내를 하기보다는 눈부신 노력을 하는 편이 쉽다.",

      author: "라 브뤼에르",

    },

    {

      quote:

        "무기력을 극복할 수 있는 유일한 방법은 열정이다.",

      author: "토인비",

    },

    {

      quote: "배우지 않으면, 곧 늙고 쇠해진다.",

      author: "주자",

    },

    {

      quote: "불행을 극복하는 유일한 것은 열심히 노력하는 것이다.",

      author: "해리 골든",

    },

    {

      quote: "슬픔이나 좌절이 생겼다 해도 해 지기 전에 반드시 즐겁게 보낼 시간을 따로 마련하라.",

      author: "얼 라이팅게일",

    },

    {

      quote: "실패하는 자가 패배하는 것이 아니라 포기하는 자가 패배하는 것이다.",

      author: "장 파울",

    },

    {

      quote: "옷을 입으면 추위를 막듯이 인내가 불의를 막아줄 것이다.",

      author: "레오나르도 다빈치",

    },

    {

      quote: "인내가 최상의 미덕이다.",

      author: "카토",

    },

    {

      quote: "인내는 쓰지만 그 열매는 달다.",

      author: "아리스토텔레스",

    },

  ];

  

  const quote = document.querySelector("#quote span:first-child");

  const author = document.querySelector("#quote span:last-child");

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

  

  quote.innerText = todaysQuote.quote;

  author.innerText = todaysQuote.author;

 

 

배경화면 4개 무작위로 나타내기

const images = [

    "0.jpg""1.jpg""2.jpg""3.jpg"

];

 

const chosenImage = images[Math.floor(Math.random() * images.length)];

 

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

 

bgImage.src = `img/${chosenImage}`;

 

document.body.appendChild(bgImage)

 

 

 

To Do List 작성

const toDoForm = document.getElementById("todo-form");

const toDoInput = document.querySelector("#todo-form input");

const toDoList = document.getElementById("todo-list");

const TODOS_KEY = "todos";

let toDos = [];

function saveToDos() {

  localStorage.setItem(TODOS_KEYJSON.stringify(toDos));

}

 

function deleteToDo(event) {

  const li = event.target.parentElement;

  console.log(li.id);

  li.remove();

  toDos = toDos.filter((toDo=> toDo.id !== parseInt(li.id));

  saveToDos();

}

 

function paintToDo(newTodo) {

  const li = document.createElement("li");

  li.id = newTodo.id;

  const span = document.createElement("span");

  span.innerText = newTodo.text;

  const button = document.createElement("button");

  button.innerText = "❌";

  button.addEventListener("click"deleteToDo);

  li.appendChild(span);

  li.appendChild(button);

  toDoList.appendChild(li);

}

function handleToDoSubmit(event) {

  event.preventDefault();

  const newTodo = toDoInput.value;

  toDoInput.value = "";

  const newTodoObj = {

    text: newTodo,

    id: Date.now(),

  };

  toDos.push(newTodoObj);

  paintToDo(newTodoObj);

  saveToDos();

}

toDoForm.addEventListener("submit"handleToDoSubmit);

const savedToDos = localStorage.getItem(TODOS_KEY);

if (savedToDos !== null) {

  const parsedToDos = JSON.parse(savedToDos);

  toDos = parsedToDos;

  parsedToDos.forEach(paintToDo);

}

 

입력값이 널값이면 오류 및 메시지 보여주기

 

 

 

로그인 기능

const loginForm = document.querySelector("#login-form");

const loginInput = document.querySelector("#login-form input");

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

 

const HIDDEN_CLASSNAME = "hidden";

const USERNAME_KEY = "username";

 

function onLoginSubmit(event) {

  event.preventDefault();

  loginForm.classList.add(HIDDEN_CLASSNAME);

  const username = loginInput.value;

  localStorage.setItem("username"username);

  localStorage.setItem(USERNAME_KEYusername);

  paintGreetings(username);

}

 

function paintGreetings(username) {

  greeting.innerText = `Hello ${username}`;

  greeting.classList.remove(HIDDEN_CLASSNAME);

}

 

loginForm.addEventListener("submit"onLoginSubmit);

const savedUsername = localStorage.getItem(USERNAME_KEY);

 

if (savedUsername === null) {

  loginForm.classList.remove(HIDDEN_CLASSNAME);

  loginForm.addEventListener("submit"onLoginSubmit);

else {

  paintGreetings(savedUsername);

}

 

버튼 클릭 시 텍스트 값을 받아 화면에 표시
데이터 저장
To Do List 작성

X 버튼 클릭 시 리스트 삭제

 

데이터 저장

'웹 코딩 > 개인 프로젝트' 카테고리의 다른 글

그림판 만들기  (0) 2021.08.18