본문 바로가기
공부/javascript

2022.06.23 - (+계속 추가) 노마드 크롬웹앱 내 맘대로 수정하기

by 기묜몬 2022. 6. 23.

1. 날씨 아이콘 추가 

나의 크롬웹앱이 너무 심심해보여서 날씨 아이콘을 추가해봤다. 

크롬웹앱에 뭔가 하나씩 추가할 예정이다.

(추가 계획은 내가 있는 장소 코로나확진자수 보여주기 )

 

날씨 아이콘을 어떻게 추가하면 좋을지 좀 고민을 했는데 내가 선택한 방식은

1) 날씨 아이콘 이미지 폴더를 프로젝트 폴더에 넣는다 .

2) weather div 안에 img태그 하나 생성한다.

3) weather js 파일에 날씨 조건에 맞는 아이콘을 이미지로 불러오겠다는 코드를 작성한다.

4) setAttribute 확장자명 꼭 붙이기 (.png ...) 

 

그리고 잊으면 안되는 것.

날씨 이미지명을 openweathermap main의 날씨명으로 맞춰주기!! 짜란 잘 나온다~~

( 날씨 아이콘 보니까 낮/밤 나뉘어져 있던데,, 그거까진 넘 멀리가는 것 같아서 낮 아이콘만 사용함 )

[ js ]

function onOk(position) {
  //위도
  const lat = position.coords.latitude;
  //경도
  const lng = position.coords.longitude;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`;
  console.log(url);
  //
  fetch(url)
    .then((Response) => Response.json())
    .then((data) => {
      const iconSelect = document.querySelector(".weather .weather__icon");
      const icon = data.weather[0].main;
      const weather = document.querySelector(".weather span:nth-child(2)");
      const city = document.querySelector(".weather span:nth-child(3)");
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
      city.innerText = data.name;
      iconSelect.setAttribute("src", `./img/icons/${icon}.png`);
    });
  // fetch -> response -> json ()
}
function onError() {
  alert("날씨 에러 ! ");
}

navigator.geolocation.getCurrentPosition(onOk, onError);
//getCurrentPosition(실행함수, 에러가 발생했을때 실행할 함수)

 

 

[ 에러 ]

사실 첨에 살짝 놓쳤던 부분이 있다. img 태그에서 src="" 이부분에  data.weather.icon 입력ㅎ

weather은 왜 자꾸 집착해서 붙였는지.. ?

암튼 너무 초보스러운 실수지만 같은 실수를 반복하면 안되기에 적는다..

   <div class="weather">
        <img
          width="30"
          class="weather__icon"
          src="${data.icon}"
          alt="weatherIcon Error"
        />
        <span></span>
        <span></span>
      </div>

 

 

2. 등록, 하트 버튼 추가 

1) 등록 버튼으로도 일정을 등록할 수 있도록 한다. (엔터, 등록 둘다가능)

등록 버튼을 생성한 뒤 버튼에 이미 만들어진 함수 todolist를 생성할 수 있도록 클릭 이벤트를 줬다. 

2) 중요한 일정은 하트를 누를 수 있도록 한다.

metarial-icons를 이용하여 i태그를 생성하고, 이벤트 타겟을 사용하여 클릭시 빈 하트에서 꽉찬 하트로 i태그 innertext를 변경하도록 했다.

[ js - (2)번 ]

if문, 삼항연산자 둘 중 하나를 사용하면 되는데 아직은 if문이 더 익숙하다. 

  like.addEventListener("click", (e) => {
    const target = e.target;
    if (target.innerText === "favorite") {
      target.innerText = "favorite_border";
    } else {
      target.innerText = "favorite";
    }
  });

문제는 클릭했을때 꽉찬 하트가 새로고침될때 기억해야하는데 다시 빈하트로 돌아옴.. 흠..