vanilla js로 할 일 목록 만들기
vanilla js로 내 위치의 날씨 만들기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
margin-top: 0px;
margin-left: 0px;
width: 100%;
height: 100%;
}
div {
color: white;
}
main {
width: 100%;
height: 100%;
position: relative;
}
img {
position: absolute;
}
#weather {
position: absolute;
right: 0px;
width: 150px;
height: 150px;
z-index: 1;
}
</style>
</head>
<body>
<main>
<div id="weather"></div>
<img id="img" src="" width="1920px" height="1080px" z-index="0" />
<div
style="
z-index: 1;
position: relative;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
"
>
<div>
<h1 id="clock"></h1>
<div id="nameWrapper">
<input id="name" name="name" />
<button id="name_submit" onclick="namesubmit()">제출</button>
</div>
<div>
<input name="to-do" id="to-do" />
<button id="addButton" onclick="add()">추가</button>
<ul id="do-list"></ul>
</div>
</div>
</div>
</main>
<script>
const imgs = [
"./homeWork_src/1.jpg",
"./homeWork_src/2.jpg",
"./homeWork_src/3.jpg",
];
const image = document.getElementById("img");
const index = Math.floor(Math.random() * imgs.length);
image.src = imgs[index];
const clock = document.getElementById("clock");
const getClock = () => {
const date = new Date();
const hour = String(date.getHours()).padStart(2, "0");
const min = String(date.getMinutes()).padStart(2, "0");
const sec = String(date.getSeconds()).padStart(2, "0");
clock.innerText = `${hour}:${min}:${sec}`;
};
getClock();
setInterval(getClock, 1000);
const namesubmit = () => {
console.log("test");
const name = document.getElementById("name");
const nameWrapper = document.getElementById("nameWrapper");
if (name.value === "이름") {
nameWrapper.innerHTML = `<div>Hello, ${name.value}님!</div>`;
}
};
let todolist = localStorage.getItem("todolist");
if (
todolist === null ||
todolist === undefined ||
todolist.length === 0
) {
todolist = [];
} else {
todolist = todolist.split(",");
for (const key in todolist) {
const do_list = document.getElementById("do-list");
const to = document.createElement("li");
to.textContent = todolist[key];
do_list.appendChild(to);
const deleteButton = document.createElement("button");
deleteButton.textContent = "삭제";
deleteButton.addEventListener("click", function () {
todolist.splice(key, 1);
localStorage.setItem("todolist", todolist);
this.parentNode.remove();
});
to.appendChild(deleteButton);
}
}
function add() {
const todo = document.getElementById("to-do");
const do_list = document.getElementById("do-list");
const to = document.createElement("li");
do_list.appendChild(to);
to.textContent = todo.value;
todolist.push(todo.value);
localStorage.setItem("todolist", todolist);
const deleteButton = document.createElement("button");
deleteButton.textContent = "삭제";
deleteButton.addEventListener("click", function () {
console.log(this.parentNode.textContent);
const splitWord = String(this.parentNode.textContent).slice(0, -2);
console.log(splitWord);
const index = todolist.indexOf(splitWord);
todolist.splice(index, 1);
localStorage.setItem("todolist", todolist);
this.parentNode.remove();
});
to.appendChild(deleteButton);
todo.value = "";
}
const weather = document.getElementById("weather");
const weatherApi = () => {
navigator.geolocation.getCurrentPosition(async (e) => {
console.log(e);
const result = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${e.coords.latitude}&lon=${e.coords.longitude}&appid={APIKey}&units=metric`
)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
weather.innerText = `${data.main.temp} @ ${data.name}`;
});
console.log(result);
});
};
weatherApi();
</script>
</body>
</html>
지난번에 이어서 코드를 몇가지 수정했다.
let todolist = localStorage.getItem("todolist");
if (
todolist === null ||
todolist === undefined ||
todolist.length === 0
) {
todolist = [];
} else {
todolist = todolist.split(",");
for (const key in todolist) {
const do_list = document.getElementById("do-list");
const to = document.createElement("li");
to.textContent = todolist[key];
do_list.appendChild(to);
const deleteButton = document.createElement("button");
deleteButton.textContent = "삭제";
deleteButton.addEventListener("click", function () {
todolist.splice(key, 1);
localStorage.setItem("todolist", todolist);
this.parentNode.remove();
});
to.appendChild(deleteButton);
}
}
먼저 로컬스토리지에 투두 리스트가 이미 있는 경우라면 미리 불러와서 todo list에 자식으로 들어가게끔 해주었다.
삭제해야할 때를 위해 미리 배열의 인덱스 값을 넣어 원하는 위치의 요소를 제거하고 로컬스토리지에 저장하게끔 해주었다.
const weather = document.getElementById("weather");
const weatherApi = () => {
navigator.geolocation.getCurrentPosition(async (e) => {
console.log(e);
const result = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${e.coords.latitude}&lon=${e.coords.longitude}&appid={APIKey}&units=metric`
)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
weather.innerText = `${data.main.temp} @ ${data.name}`;
});
console.log(result);
});
};
weatherApi();
날씨 API를 요청하는 부분이다.
현재 위치 정보를 얻어오고 얻어온 정보를 활용하여 API 요청을 보낸다.
어느정도 익숙해진건지 크게 부담스럽진 않은 과제였다.
본 후기는 유데미-스나이퍼팩토리 10주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.
#프로젝트캠프 #프로젝트캠프후기 #유데미 #스나이퍼팩토리 #웅진씽크빅 #인사이드아웃 #IT개발캠프 #개발자부트캠프 #리액트 #react #부트캠프 #리액트캠프