-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJs2(javaScript).js
More file actions
241 lines (188 loc) · 8.55 KB
/
Js2(javaScript).js
File metadata and controls
241 lines (188 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const logInForm = document.querySelector("#login-form");
const logInPut = logInForm.querySelector("input");
const greeting = document.querySelector("#greeting");
const HIDDEN_CLASSNAME = "hidden";
const USERNAME_KEY = "username";
const TODOS_KEY = "todos";
//localStorage.setItem(const , 변수) 웹페이지의 데이터베이스에 아이템을 저장가능
//localStorage.getItem(const) 저장되어있는 값을 꺼내기 가능
//localStorage.removeItem(const) 저장되어있는 값 삭제 가능
function onLoginSubmit(event) {
event.preventDefault();
logInForm.classList.add(HIDDEN_CLASSNAME);
const username = logInPut.value;
localStorage.setItem(USERNAME_KEY, username);
paintGreetings(username);
}
function paintGreetings(username) {
greeting.innerText = `Hello ${username}`;
// 백틱 기호는 1옆의 원화 기호이다.
greeting.classList.remove(HIDDEN_CLASSNAME);
}
//localStorage에서 저장되어있는 값 꺼내기
const savedUsername = localStorage.getItem(USERNAME_KEY);
//저장되어있는 값이 없다면
if (savedUsername === null) {
logInForm.classList.remove(HIDDEN_CLASSNAME);
logInForm.addEventListener("submit", onLoginSubmit);
//loginform 보여주기
} else {
//저장되어있는 값이 있다면 greeting 출력
paintGreetings(savedUsername);
}
//clock.js
const clock = document.querySelector("h2#clock");
//몇초의 간격동안 어떤 함수를 계속 반복 작동시킬 수 있는 함수 setInterval
//인자를 두개 받는다 함수 인자 하나, 몇초의 간격을 할것인지를 인자로 받는다. 인자 2개.
//단위는 ms 5000ms=5초
//setInterval()
//웹사이트를 열자마자 함수를 실행하는것이 아닌 조금 기다리고 싶을때 쓰는 함수.
//인자를 받는건 setInterval과 동일
//setTimeout()
//Date object 날짜와 관련된 값들을 다루는 객체
//getFullYear getHours getMinutes getDatees getSeconds 함수 지원
function setDate() {
const date = new Date();
const hour = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const second = String(date.getSeconds()).padStart(2, "0");
//함수 안에 생성해주어야한다. 1초마다 새로운 객체를 생성해 업데이트하는 방식
clock.innerText = `${hour}:${minutes}:${second}`;
}
setDate(); // 즉시 호출
setInterval(setDate, 1000); // 1초마다 업데이트
//PadStart
//"1".padStart(2,"0") 앞쪽 부분의 string을 늘리고, 앞쪽에 0를 추가한다. 인자를 두개받는다.
//"2".padEnd(3,"0") 뒤쪽 부분의 string을 늘리고, 뒤쪽에 0을 추가
//Quote
const quotes = [
{
quote: "The way to get started is to quit talking and begin doing.",
author: "Walt Disney",
},
{
quote: "Life is what happens when you're busy making other plans.",
author: "John Lennon",
},
{
quote:
"The world is a book and those who do not travel read only one page.",
author: "Saint Augustine",
},
{
quote: "Life is either a daring adventure or nothing at all.",
author: "Helen Keller",
},
{
quote: "To Travel is to Live",
author: "Hans Christian Andersen",
}, {
quote: "Only a life lived for others is a life worthwhile.",
author: "Albert Einstein",
},
{
quote: "You only live once, but if you do it right, once is enough.",
author: "Mae West",
},
{
quote: "Never go on trips with anyone you do ntot love.",
author: "Hemmingway",
},
{
quote: "We wander for distraction, but we travel for fulfilment.",
author: "Hilaire Belloc",
},
{
quote: "Travel expands the mind and fills the gap.",
author: "Sheda Savage",
},
];
const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");
//Math.random() - java와 사용법 동일 floor 내림 메소드
const quo = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = quo.quote;
author.innerText = quo.author;
//BackGround
const images = ["1.jpeg", "2.jpeg", "3.jpeg"];
const chosenImages = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImages}`;
document.body.appendChild(bgImage)
//toDo List
const toDoForm = document.getElementById("todo-form");
const toDoList = document.getElementById("todo-list");
const toDoInput = toDoForm.querySelector("input");
let toDos = [];
function saveToDos() {
//localStorage.setItem("todos", toDos);
//string 형태로 저장되어있음. 가,나,다, 이런식으로 실제로 array는 아니다.
localStorage.setItem(TODOS_KEY, JSON.stringify(toDos));
//const result = localStorage.getItem("todos");
//const parseResult = JSON.parse(result);
/* localStorage.setItem("todos", toDos);
const result = localStorage.getItem("todos");
console.log(result);
console.log(result[0]);
*/
//boring string , array 형태로 parsing 해주어야한다.
}
function deleteToDo(event) {
//event에 대한 정보를 이용해 어떤 li를 제거해야하는지 알 수 있다. event.target parentElement를 알아야한다. 부모 elemet가 누군지 알면 그 부모를 삭제하면됨.
const li = event.target.parentElement;
li.remove(); //target을 통해 정보를 가져온 후, 그 정보를 통해 부모 element가 무엇인지 알아낸다.
toDos = toDos.filter(toDo => toDo.id !== parseInt(li.id)); // li.id의 타입은 string이다. 파싱해줘야하는것.
saveToDos();
}
function paintToDo(newTodo) {
const li = document.createElement("li");
li.id = newTodo.id;
const span = document.createElement("span");
span.innerText = newTodo.text; //span 안에 내용 적기
const button = document.createElement("button");
button.innerText = "X";
button.addEventListener("click", deleteToDo);
//마지막에 추가하여야한다.
li.appendChild(span); //li 안에 span 추가하기
li.appendChild(button);
toDoList.appendChild(li); // li를 toDoList에 추가하기
}
function handleTodo(event) {
event.preventDefault();
const newTodo = toDoInput.value; //input값 변수에 저장
toDoInput.value = ""; //input 값 비우기
const newTodoObj = {
text: newTodo,
id: Date.now(),
};//랜덤한 아이디 생성을 위해서 오브젝트 생성
toDos.push(newTodoObj); //stack처럼 작용.
paintToDo(newTodoObj);
saveToDos();
}
//form에 eventListener을 추가해야함. input에 추가하면안된다. form의 default가 제출 submit이기때문에
toDoForm.addEventListener("submit", handleTodo);
const savedToDos = localStorage.getItem(TODOS_KEY);
if (savedToDos !== null) {
const parsedToDos = JSON.parse(savedToDos);
toDos = parsedToDos;
//객체들의 배열로 만들어줌. 문자열들의 배열로 만들어줌 array 형태
parsedToDos.forEach(paintToDo);
//array 들의 각 요소들에 접근하게 해줌. forEach
//sayHello(item) -> 각 요소들을 인자들로 받게 된다.
//parsedToDos.forEach(item) => console.log("this is the turn of ", item) 이렇게 진행도 가능
//function 정의 필요없이. 이를 arrow fuction이라고 한다. 두 방법은 동일하다.
//새롭게 추가한 요소들과 저장되어있는 요소들 모두 저장하고싶다.
//toDos array가 application이 실행될때 항상 비어있기 때문에 위의 기능이 이루어지지않는다.
//let toDos = [] ; 업데이트 가능하게 만들고, savedToDos가 비어있지 않다면, toDos를 업데이트하고 paintTodo하여 화면에 띄워준다.
//새로고침하여도 동일한 todolist를 띄워준다.
}
//Delete 기능 수행 수정해야함.
//todo array에 id를 삽입해주고싶다. 어떤 요소가 선택되고 삭제되는지 알기 위해서
//랜덤한 숫자를 각 id로 삽입해주는 기능을 만들고 싶다. date.now 활용
//배열에서 아이템을 삭제하는 것은 지우고 싶은 아이템을 제외하고 새로운 배열을 만들어준다.
//.filter() 괄호안에 들어가는 것이 boolean, 즉 true를 반환한다면 그 아이템을 제거해주는 메소드
//.filter()는 항상 새로운 배열을 반환해준다.
//Weather
navigator.geolocation.getCurrentPosition(); // 사용자의 위치에 관한 정보
//getCurrentPosition(true, false); 각각 진실일때 함수, 거짓일때 함수를 인자로 넣어야함.
//function(position) { =position.cords.latitude}