웹/Javascript

[JavaScript]_todo + weather + corona_code

Ellie67 2021. 2. 16. 23:01

backGround.js

- 새로고침하면 배경이 랜덤 설정된다.

const body = document.querySelector("body"); // 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element 반환. 일치하는 요소 없으면 null 반환

const IMG_NUMBER = 5; // 다섯개의 이미지

function paintImage(imageNum){
    const image = new Image();
    image.src = `images/${imageNum}.jpg`;
    image.classList.add("bgImage");
    body.prepend(image); // body의 첫 번째 자식 이전에 image를 삽입
}

function randomNum(){
    const num = Math.floor(Math.random() * IMG_NUMBER + 1); // 배경이미지를 랜덤으로 하기 위함. 소수가 나올 수 있기 때문에 Math.floor을 사용해서 같거나 작은 정수 중에서 가장 큰 수를 반환하도록 함
    return num;
}

function init(){
    const number = randomNum();
    paintImage(number);
}
init();

 

 


 

clock.js

- 시간 출력

const clock = document.querySelector(".js-clock");
const clockTitle = clock.querySelector("h1");

function getTime(){
    const date = new Date(); 
    const hours = date.getHours(); 
    const minutes = date.getMinutes();
    const seconds = date.getSeconds(); 
    clockTitle.innerText =
    `${hours < 10 ? `0${hours}` : hours} : ${minutes <  10 ? `0${minutes}` : minutes} : ${seconds < 10 ? `0${seconds}` : seconds}`; // 시,분,초가 한자리 수일 때 앞에 0을 붙여줌
}

function init(){
    getTime();
    setInterval(getTime, 1000); 
}
init();

 

clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours} : ${minutes <  10 ? `0${minutes}` : minutes} : ${seconds < 10 ? `0${seconds}` : seconds}`;

- 시,분,초가 한자리 수일 때 앞에 0을 붙여줌

 

setInterval(getTime1000);

- 1000밀리세컨드(1초) 간격으로 getTime 함수 호출

 

 


welcome.js

- 클라이언트가 이름을 입력하면 입력 폼이 사라지고 'Hello name' 가 보여진다.

localStorage에 이름이 저장되어 새로고침을 해도 유지된다.

const form = document.querySelector(".js-form")
const input = form.querySelector("input");
const welcome = document.querySelector(".js-welcome");

const USER = "currentUser";
const SHOWING = "showing";

function saveName(text){
    localStorage.setItem(USER, text); // localStorage에 저장
}

function handleSubmit(event){
    event.preventDefault(); // 이벤트 발생 안 함
    const currentValue = input.value;
    paintWelcome(currentValue);
    saveName(currentValue);
}

function askName(){
    form.classList.add(SHOWING); // 폼 클래스
    form.addEventListener("submit",handleSubmit); // 이름 제출
}

function paintWelcome(user){
    form.classList.remove(SHOWING); // 폼 지우고
    welcome.classList.add(SHOWING); // welcome 클래스
    welcome.innerText = `Hello ${user}!`; // welcome 텍스트
}

function loadName(){
    const currentUser = localStorage.getItem(USER);
    if(currentUser === null){
        askName(); // 폼이 비어있으면 유저 이름 요청
    } else{
        paintWelcome(currentUser); // 이름을 입력했으면 환영해줌
    }
}

function init(){
    loadName();
}
init();

 

 


 

check.js

-todo list를 만든다.

welcome.js에서와 마찬가지로 localStroage에 list 내용이 저장되어 새로고침 해도 리스트가 유지된다.

const checkForm = document.querySelector(".js-checkForm");
const checkInput = checkForm.querySelector("input");
const checkList = document.querySelector(".js-checkList");

const CHECK_LS = "lists";

let lists = []; // 리스트 배열을 만듦

function saveList(){
    localStorage.setItem(CHECK_LS, JSON.stringify(lists)); // 리스트를 json 문자열로 변환하고 localstorage에 저장
}

function deleteList(event){ // delBtn 클릭시
    const btn = event.target;
    const li = btn.parentNode;
    checkList.removeChild(li); 
    const cleanList = lists.filter(function(list){ // filter 함수가 새로운 배열로 만들어줌
        return list.id !== parseInt(li.id);
    });
    lists = cleanList;
    saveList();
}

function paintList(text){
    const li = document.createElement("li"); //  요소 추가
    const delBtn = document.createElement("button");
    const span = document.createElement("span");
    const newId = lists.length + 1; 
    delBtn.innerText = "❌"; // 리스트 지울 수 있는 버튼
    delBtn.addEventListener("click", deleteList); 
    span.innerText = text; // span에 입력한 todo 넣어줌
    li.id = newId; // 리스트마다 아이디 생성
    li.appendChild(delBtn); // li에 delBtn을 자식으로 
    li.appendChild(span); // li에 span을 자식으로
    checkList.appendChild(li); // html에 생성한 checkList에 li를 자식으로 
    const listObj = {
        text:text,
        id:newId
    } // 입력한 todo list의 텍스트와 아이디를 객체로
    lists.push(listObj); // 리스트에 객체 푸시
    saveList();
}

function handleSubmit(event){
    event.preventDefault(); // 동작 중단
    const currentValue = checkInput.value;
    paintList(currentValue);
    checkInput.value=""; // 공백으로 만들어 줌
}

function loadCheck(){
    const loadedCheck = localStorage.getItem(CHECK_LS);
    if(loadedCheck !== null){
        const parsedList = JSON.parse(loadedCheck); // 구문 분석, 객체 생성
        parsedList.forEach(function(list){ // 객체 각각 마다 함수 실행
            paintList(list.text); // list 내용 가져옴
        })
    }
}

function init(){
    loadCheck();
    checkForm.addEventListener("submit", handleSubmit); // submit 이벤트가 발생했을 경우 handleSubmit으로
}
init();

 

 


 

weather.js

- api를 얻어서 그 지역의 날씨를 알려준다.

const weather = document.querySelector(".js-weather");
const API_KEY = "bbb87f7ae736a19add23c19543c2c765"; // 날씨 api를 이용하기 위한 키
const COORDS = "coords";

function toggle_wea(id) { // weather 버튼을 클릭할 때만 보이게 하기 위해서
    const weather_span = document.getElementById(id);
    if(weather_span.style.display == 'block') {
        weather_span.style.display = 'none';
    }
    else {
        weather_span.style.display = 'block';
    }
    return;
}

function getWeather(lat, lon){
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`)
    .then(function(response){
        return response.json();
    }).then(function(json){
        const temp = json.main.temp; 
        const place = json.name;
        const status = json.weather[0].main;
        weather.innerText = `[Temperature] : ${temp} °C
        [Location] : ${place}
        [State] : ${status}`;
    }).catch(error => console.log('error', error));
}

function saveCoords(coordsObj){
    localStorage.setItem(COORDS, JSON.stringify(coordsObj)); // 위치를 localStorage에 저장
}

function handleGeoSuccess(position){
    const latitude = position.coords.latitude; // 위도
    const longitude = position.coords.longitude; // 경도
    const coordsObj = {
        latitude, longitude
    }; // 위도와 경도를 하나의 객체로
    saveCoords(coordsObj);
    getWeather(latitude,longitude);
}

function handleGeoError(){
    console.log("Cant access");
}

function askForCoords(){
    navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError); // 웹에서 장치의 위치를 알아낼 때 사용
}

function loadCoords(){
    const loadedCoords = localStorage.getItem(COORDS);
    if(loadedCoords === null){
        askForCoords();
    } else {
        const parseCoords = JSON.parse(loadedCoords);
        getWeather(parseCoords.latitude, parseCoords.longitude);
    }
}

function init(){
    loadCoords();
}
init();

 

OpenWeather

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on global and local weather models, satellites, radars and vast network of weather stations. how to obtain APIs (subscriptions with di

openweathermap.org

=> OpenWeather을 통해 날씨 api를 얻었다.


 

corona.js

- api를 얻어서 그 국가의 코로나 상황을 알려준다. 

const corona = document.querySelector(".js-corona");
const APIKEY = "f4b8e044593a64faa4f76af25c3f8d71df090298a9e2b3d1016b9662"; // api를 이용하기 위한 키

function toggle_coro(id) { // corona 버튼을 클릭했을 때만 보이기 위해
  const corona_span = document.getElementById(id);
  if(corona_span.style.display == 'block') {
    corona_span.style.display = 'none';
  }
  else {
    corona_span.style.display = 'block';
  }
  return;
}

function getStatus(country){ // 코로나 상황 얻기 위해
  fetch(`https://api.covid19api.com/live/country/${country}/status/confirmed`)
  .then(function(response){
    return response.json();
  }).then(function(json){
    const day = Object.keys(json).length-1;
    const confirmed = json[day].Confirmed;
    const deaths = json[day].Deaths;
    const recovered = json[day].Recovered;
    corona.innerText = 
    `[${country}] 
    Deaths : ${deaths}
    Confirmed : ${confirmed} 
    Recovered : ${recovered}`;
  }).catch(error => console.log('error', error));
}

function getIp() {
    fetch(`https://api.ipdata.co?api-key=${APIKEY}`) // ip 주소 얻기 위해
    .then(function(response){
        return response.json();
    }).then(function(json){
        getCountry(json.ip);
    });
}
function getCountry(ip){ // 국가 정보 얻기 위해
  fetch(`https://ipapi.co/${ip}/json/`)
  .then(function(response){
  response.json()
  .then(jsonData => {
    getStatus(jsonData.country_name);
  });
}).catch(function(error) {
  console.log(error)
  });
} 

function init(){
    getIp();
  }
  init();

 

ipdata

 

Dashboard - ipdata

Loading... Here's your API key. Keep it safe. If you need to get an API key changed or revoked, please contact us.

dashboard.ipdata.co

=> ip 주소를 얻기 위해 ipdata를 이용했다. 접속 국가도 알 수 있었지만 도시 정보가 정확하지 않은 것 같아서 이곳에서는 ip주소만 얻고 다른 곳에서 국가 정보를 얻기로 했다.

 

 

ipapi

 

ipapi - API Reference | IP Location Examples

Introduction Documentation for IP address location API ipapi.co provides a REST API to find the location of an IP address. Specifically, you can get the following information for any IP address: city, region (name & code), country (name & code), continent,

ipapi.co

=> ipdata에서 얻은 ip를 이용하여 ipapi에서 국가 정보를 얻었다. js코드도 있어서 바로 구현할 수 있었음

 

 

Coronavirus COVID19 API

=> 위에서 얻은 국가 정보로 코로나 정보를 얻었다.

 

 

api 활용 도움받은 곳


 

 

' > Javascript' 카테고리의 다른 글

[JavaScript]_guessingGame  (0) 2021.02.26
[JavaScript]_todo + weather + corona  (0) 2021.02.16
[JavaScript]_classList  (0) 2021.02.05