const clock = document.querySelector("#clock");
function getClock() {
const date = new Date();
clock.innerText = (`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`)
}
getClock();
setInterval(getClock, 1000); //1초마다 갱신
현재 시간을 잘 나타내고 있지만,
"9" 일의 자리로 표현되는게 아니라 두 자리로 "00"표현되고 싶다.
padStart()를 사용해서 padding을 추가해달라고 자바스크립트로 요청하면된다!
"1".padStart(2,"0") //두 자리수로 보이게하고, 패딩스타트를 0으로 채운다.
'01'
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);
궁금증 : 근데 왜 Date라는 객체를 바로 안쓰고 new로 새로운 객체를 만드는가?
해결 : new Date() 객체를 date 변수에 할당함으로써, 이후 코드에서 getHours(), getMinutes(), 그리고 getSeconds()와 같은 Date 객체의 여러 속성과 메소드에 접근할 수 있다.
따라서, new Date()는 현재 시간을 나타내는 새로운 Date 객체를 생성하여, 해당 시간의 시, 분, 초를 가져올 수 있도록 하는 데 필요하다.
const 지정할변수 = new 생성자()
뭐.. 태생적으로 이런 식으로 생겨먹은 애들이라고 하니 더 이상 근본적으로 파고들어봤자 이해못할거 같아서 '그런갑다'하고 받아들였습니다
Math.floor는 소수점을 버리는 것(버림),
Math.ceil은 소수점을 올리는 것(올림),
Math.round는 소수점을 반올림/반내림 하는 것
const quotes = [{
quote: 'I never dreamed about success, I worked for it',
author: 'Estee Lauder'
},
{
quote: 'Do not try to be original, just try to be good.',
author: 'Paul Rand'
},
{
quote: 'Do not be afraid to give up the good to go for the great',
author: 'John D. Rockefeller'
},
{
quote: 'If you cannot fly then run. If you cannot run, then walk. And if you cannot walk, then crawl, but whatever you do, you have to keep moving forward.',
author: 'Martin Luther King Jr.'
},
{
quote: 'Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.',
author: 'Thomas Edison'
},
{
quote: 'The fastest way to change yourself is to hang out with people who are already the way you want to be',
author: 'REid Hoffman'
},
{
quote: 'Money is like gasoline during a road trip. You do not want to run out of gas on your trip, but you are not doing a tour of gas stations',
author: 'Tim O Reilly'
},
{
quote: 'Some people dream of success, while other people get up every morning and make it happen',
author: 'Wayne Huizenga'
},
{
quote: 'The only thing worse than starting something and falling.. is not starting something',
author: 'SEth Godin'
},
{
quote: 'If you really want to do something, you will find a way. If you do not, you will find an excuse.',
author: 'Jim Rohn'
},
];
const quote = document.querySelector("#quoteMessage");
const author = document.querySelector("#author");
todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
const images = [
"testImg1.jpg",
"testImg2.jpg",
"testImg3.jpg"
];
const chosenImg = images[Math.floor(Math.random() * images.length)];
const backgroundImg = document.createElement("img");
backgroundImg.src = `img/${chosenImg}`
document.body.appendChild(backgroundImg);
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input");
const toDoList = document.getElementById("todo-list");
const toDos = [];
function saveToDos(){
localStorage.setItem("toDos", JSON.stringify(toDos));
}
function deleteToDo(event){
const li = event.target.parentElement;
li.remove();
}
function paintToDo(newTodo){
const list = document.createElement("li");
const todoContent = document.createElement("span");
const button = document.createElement("button");
button.innerText = "❌";
button.addEventListener("click", deleteToDo);
list.appendChild(todoContent);
list.appendChild(button);
todoContent.innerText = newTodo;
toDoList.appendChild(list);
}
function handleTodoSubmit(event) {
event.preventDefault();
const newTodo = toDoInput.value;
toDoInput.value = "";
paintToDo(newTodo);
toDos.push(newTodo);
saveToDos();
}
toDoForm.addEventListener("submit", handleTodoSubmit);
알게된점
STRINGIFY = 변수 등을 문자열로 바꿈,PARSE = 문자열을 JSON으로 바꿈
toDoForm.addEventListener("submit", handleTodoSubmit);
function sayHello(){
console.log("say hello");
}
const savedToDos = localStorage.getItem(TODOS_KEY);
if(savedToDos !== null){
const paresdToDos = JSON.parse(savedToDos);
console.log(paresdToDos);
paresdToDos.forEach(sayHello);
}
function onGeoOk(position){
const lat = position.coords.latitude; //위도
const lng = position.coords.longitude; //경도
console.log("You live it", lat, lng);
}
function onGeoError(){
alert("Can't find you, No weather for you")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
navigator.geolocation.getCurrentPosition ( ) 라는 코드를 작성해준다.
이때 getCurrentPosition 은 2개의 argument가 필요하다. 앞쪽에는 모든 게 잘 됐을 때 실행될 함수인 onGeoOk 함수를, 뒤에는 실패했을 때 실행될 함수인 onGeoError 함수를 입력한다.
onGeoError() 함수가 실행될 때 :
에러가 났다는 것을 사용자에게 알려주기 위해서
alert("Can't find you. No weather for you."); 를 해준다.
onGeoOk 함수가 실행될 때:
function onGeoOk(position){
const lat = position.coords.latitude;
const lng = position.coords.longitude;
console.log("You live in", lat, lng);
}
자바스크립트가 position으로 user의 위치를 전달해준다.
position은 object 이고 위도와 경도 값이 들어있다. positon.coords.latitude와
position.coords.longitude 를 변수에 저장하고 console.log를 해서 사용자에게 보여준다.
지리적 위치: getCurrentPosition() 메서드를 사용해서 user의 위치와 장소 이름을 확인 할 수 있다.
사용할 API는 유명한 OpenWeatherMap API를 사용한다.
https://openweathermap.org/api
API Doc을 클릭하여 문서를 보면 된다.
문서를 보면 알 수 있다시피 여기서 제공해주는 것은 우리 지역의 현재 날씨 등을 제공해주고 있다.
문서의 밑에 부분을 보면 어떻게 API를 call 할 수 있는지가 설명되어있다.
Geolocation.getCurrentPosition()
장치의 현재 위치를 가져오는 메소드이다.
기본 문법
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
success 함수는 GeolocationPosition 객체를 유일한 매개변수로 받는 콜백 함수이다.
Weather API 이용하기
https://openweathermap.org/
계정 생성 > Current Weather Data > API doc > By geographic coordinates
function example(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}`
console.log(url)
fetch코드...
}
Geolocation API 메소드
Method 설명
getCurrentPosition() 사용자의 현재 위치를 가져옴.
watchPosition() 사용자의 현재 위치를 가져오고 나서, 사용자의 움직임에 따라 지속적으로 위치 정보를 갱신함.
clearWatch() watchPosition() 메소드의 실행을 중지함.
getCurrentPosition() 메소드의 반환 값
속성 반환값
coords.latitude 소수로 표현된 위도 값
coords.longitude 소수로 표현된 경도 값
coords.accuracy 위도 값과 경도 값의 정확도
coords.altitude 평균 해수면을 기준으로 하는 고도 값(해발)
coords.altitudeAccuracy 고도 값의 정확도
coords.heading 북쪽을 기준으로 현재 진행 방향에 대한 시계방향으로의 각도 값(˚)
coords.speed 초당 이동한 미터 수를 나타내는 속도 값(초속)
timestamp 위치 정보를 가져온 시간을 나타냄.