To Do List - 입력 시 to do list에 추가되도록
📄 index.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">
<link rel="stylesheet" href="css/style.css"/>
<title>Momentum</title>
</head>
<body>
<!-- greetings -->
<form id="login-form" class="hidden">
<input required maxlength="15" type="text" placeholder="What is your name?"/>
<input type="submit" value="Log In"/>
</form>
<!-- clock -->
<h2 id="clock">00:00:00</h2>
<!-- greetings -->
<h1 id="greeting" class="hidden"></h1>
<!-- to do list -->
<form id="todo-form">
<input type="text" placeholder="Write a To Do and Press Enter." required />
</form>
<ul id="todo-list"></ul>
<!-- quotes -->
<div id="quote">
<span></span>
<span></span>
</div>
<!-- import js -->
<script src="js/greetings.js"></script>
<script src="js/clock.js"></script>
<script src="js/quotes.js"></script>
<script src="js/background.js"></script>
<script src="js/todo.js"></script>
</body>
</html>
📄 todo.js
const toDoForm = document.getElementById("todo-form");
const toDoInput = document.querySelector("#todo-form input");
const toDoList = document.getElementById("todo-list");
function paintToDo(newTodo) {
const li = document.createElement("li"); // html "li" element 생성.
const span = document.createElement("span"); // html "span" element 생성.
li.appendChild(span); // li가 자식으로 span을 가짐.
span.innerText = newTodo;
toDoList.appendChild(li); // toDoList가 자식으로 li를 가짐.
}
function handleToDoSubmit(event) {
event.preventDefault();
const newTodo = toDoInput.value; // input의 value 저장.
toDoInput.value = ""; // input 비우기.
paintToDo(newTodo); // todo list 그리기.
}
toDoForm.addEventListener("submit", handleToDoSubmit);
To Do List - 삭제 버튼 추가
📌 event.target
: 클릭된 HTML element.
📌 event.target.parentElement
클릭된 element의 부모.
📄 todo.js
const toDoForm = document.getElementById("todo-form");
const toDoInput = document.querySelector("#todo-form input");
const toDoList = document.getElementById("todo-list");
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
}
function paintToDo(newTodo) {
const li = document.createElement("li");
const span = document.createElement("span");
span.innerText = newTodo;
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 = "";
paintToDo(newTodo);
}
toDoForm.addEventListener("submit", handleToDoSubmit);
To Do List - to do list 저장, 불러오기
📌 localStorage에는 array를 저장할 수 없음. 텍스트만 저장 가능.
📌 JSON.stringify( )
: JavaScript의 object나 array 등을 string으로 바꿔줌.
→ array 모양으로 localStorage에 저장 가능.
📌 JSON.parse( )
: string을 JavaScript가 이해하는 array 바꿔줌.
📌 [array].foreach( [function] )
: array안을 한 번씩 돌면서 지정한 함수를 실행함.
function sayHello(item) {
console.log("this is the turn of", item);
}
a.forEach(sayHello);
---------------------------------------------------------------------------------------
a.forEach((item) => console.log("this is the turn of", item));
// 위 아래 같은 내용.
📄 todo.js
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_KEY, JSON.stringify(toDos));
}
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
}
function paintToDo(newTodo) {
const li = document.createElement("li");
const span = document.createElement("span");
span.innerText = newTodo;
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 = "";
toDos.push(newTodo);
paintToDo(newTodo);
saveToDos();
}
toDoForm.addEventListener("submit", handleToDoSubmit);
const savedToDos = localStorage.getItem(TODOS_KEY);
if(savedToDos != null) {
const parsedToDos = JSON.parse(savedToDos);
toDos = parsedToDos;
parsedToDos.forEach(paintToDo);
}
To Do List - to do list 삭제 오류 수정
📌 삭제하고 새로 고침하면 삭제되지 않고 다시 뜸.
→ array만 삭제되고 localStorage에 있는 값은 삭제되지 않았기 때문.
→ to do list 저장 방식을 바꿈. (id와 text를 가지는 형태로.)
📌 Date.now( )
: 밀리초를 주는 함수.
→ 랜덤 id로 사용.
📌 [array].filter( [function] )
: array에서 item을 지우는 것은 실제로 지우는 것이 아니라, 지울 item을 제외한 새 array를 만드는 것.
array의 item을 돌면서 function을 실행하고, 반환값이 true이면 item을 유지하고, false이면 삭제함.
📄 todo.js
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_KEY, JSON.stringify(toDos));
}
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
toDos = toDos.filter((item) => item.id !== parseInt(li.id));
saveToDos();
}
function paintToDo(newToDoObj) {
const li = document.createElement("li");
li.id = newToDoObj.id;
const span = document.createElement("span");
span.innerText = newToDoObj.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);
}
weather - 현재 위치의 날씨 나타나도록
📌 navigator.geolocation.getCurrentPosition( [제대로 되었을 때 실행될 함수], [오류 발생했을 때 실행될 함수] )
: user의 위치를 알려줌.
📌 현재 위치의 날씨 받아오는 API(로그인 후 API키 받아서 사용.)
https://openweathermap.org/api
Weather API - OpenWeatherMap
Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.
openweathermap.org
https://openweathermap.org/current
Current weather data - OpenWeatherMap
Access current weather data for any location on Earth including over 200,000 cities! We collect and process weather data from different sources such as global and local weather models, satellites, radars and a vast network of weather stations. Data is avai
openweathermap.org
📌 fetch( [url] )
: JavaScript가 url을 불러옴.
promise : 시간이 지난 후 일어나는 것. 서버 응담을 기다려야 함.
📄 index.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">
<link rel="stylesheet" href="css/style.css"/>
<title>Momentum</title>
</head>
<body>
<!-- greetings -->
<form id="login-form" class="hidden">
<input required maxlength="15" type="text" placeholder="What is your name?"/>
<input type="submit" value="Log In"/>
</form>
<!-- clock -->
<h2 id="clock">00:00:00</h2>
<!-- greetings -->
<h1 id="greeting" class="hidden"></h1>
<!-- to do list -->
<form id="todo-form">
<input type="text" placeholder="Write a To Do and Press Enter." required />
</form>
<ul id="todo-list"></ul>
<!-- quotes -->
<div id="quote">
<span></span>
<span></span>
</div>
<!-- weather -->
<div id="weather">
<span></span>
<span></span>
</div>
<!-- import js -->
<script src="js/greetings.js"></script>
<script src="js/clock.js"></script>
<script src="js/quotes.js"></script>
<script src="js/background.js"></script>
<script src="js/todo.js"></script>
<script src="js/weather.js"></script>
</body>
</html>
📄 weather.js
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY = "...";
function onGeoSuccess(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}&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("navigator.geolocation.getCurrentPosition ERROR");
}
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
'클론코딩 > 노마드코더 크롬 앱' 카테고리의 다른 글
[클론코딩/크롬 앱] 노마드 코더 크롬 앱 클론코딩 #4 마무리 (0) | 2022.10.31 |
---|---|
[클론코딩/크롬 앱] 노마드 코더 크롬 앱 클론코딩 #2 Clock, Quotes, Background (0) | 2022.10.18 |
[클론코딩/크롬 앱] 노마드 코더 크롬 앱 클론코딩 #1 Login (0) | 2022.10.17 |
댓글