본문 바로가기
인강\개인공부/노마드 코더

바닐라 JS로 크롬 앱 만들기

by 꼬바리 2021. 4. 12.

바닐라 JS로 크롬 앱 만들기 결과물

 

Vanilla JS를 익히기 위해 찾다가 "노마드코더"라는 강의 사이트를 찾았습니다.

무료 강의가 좋은게 많이 있습니다.

 

초급 javaScript 를 배우고 싶으신 분들에게 추천 드립니다.

(html css 를 전혀 모르는 상태라면 어려울것이라 생각됩니다)

 

only JavaScript만으로 만든 크롬앱의 기능은

1. 시계 기능

2. 비교적 가벼운 데이터인 이름 및 todo 리스트를 브라우저 자체에 저장

3. todo리스트 삭제가능

4. 현재 위치 위도경도 값 받아 외부 날씨 api로 날씨 출력 (오른쪽 상단)

5. 랜덤 배경화면 출력

   

코드 공유 하겠습니다

 

clock.css
body {
  background-color: #34495e;
  color: white;
  margin: 0;

  text-shadow: 1px 1px 10px #000;
  /*배경에 글자가 묻혀서 글자 테두리*/

  -ms-user-select: none;
  -moz-user-select: -moz-none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
  /*글자 드래그 금지*/
}

.form,
.greetings {
  display: none;
  font-size: 40px;
}

.showing {
  display: block;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.bgImage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  animation: fadeIn 0.5s linear;
  /*배경화면 full로 채우기*/
}

#weather_top {
  text-align: right;
}

#mid {
  text-align: center;
}

.js-title {
  font-size: 100px;
}

#input_name {
  text-decoration: underline;

  background-color: transparent;
  border: none;
  /*인풋 박스 투명하게*/
  color: white;
  font-size: 30px;
  width: 280px;
}
#input_name::placeholder {
  /*인풋박스 속 글자*/
  color: white;
  text-decoration: underline;
  text-align: center;
}

#input_name:focus {
  outline: none;
}

#input_todo {
  font-size: 20px;
  background-color: transparent;
  border: none;
  color: white;
}

#input_todo::placeholder {
  color: white;
  text-decoration: underline;
  text-align: center;
}

#input_todo:focus {
  outline: none;
}
.js-toDoList {
  list-style: none;
  font-weight: bold;
}

 

 

clock.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>CLOCK_B</title>
    <link rel="stylesheet" href="clock.css" />
  </head>
  <body>


    <div class="row" id="top">
      <div class="col" id="weather_box">
        <div class="js-weather" id="weather_top"></div>
      </div>
    </div>

    <div class="row" id="mid">
      <div class="col id="main_box">
      
        <div class="js-clock">
          <h1 class="js-title"></h1>
        </div>
    
        <form class="js-form form">
          <input id="input_name" type="text" placeholder="what is your name?" />
          
        </form>
        <br>
        <h4 class="js-greetings greetings"></h4>
        <form class="js-toDoForm">
          <input id="input_todo" type="text" placeholder="Write a to do here" />
        </form>
    
        <ul class="js-toDoList"></ul>
    
      </div>
    </div>


  
    <script src="clock.js"></script>
    <script src="greeting.js"></script>
    <script src="todo.js"></script>
    <script src="bg.js"></script>
    <script src="weather.js"></script>

  </body>
</html>

 


 

 

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

function getTime() {
  const date = new Date();
  const minites = date.getMinutes();
  const hours = date.getHours();
  const seconds = date.getSeconds();

  clockTitle.innerText = `
    ${hours < 10 ? `0${hours}` : hours}:${
    minites < 10 ? `0${minites}` : minites
  }:${seconds < 10 ? `0${seconds}` : seconds}`;
  //작은 if 사용 방법 ? 백틱 :
}

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

init();

 

 

 

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

const greeting = document.querySelector(".js-greetings");

const USERS_LS = "currentUser";
const SHWING_CN = "showing";

function savaName(text) {
  localStorage.setItem(USERS_LS, text);
}

function handleSubmit(event) {
  event.preventDefault();
  //언터를 쳐도 이벤트 안날라가는것...이라고 설명 쓰면 알아듣겟냐 내가?
  const currentValue = input.value;
  console.log(currentValue);
  paintGreeting(currentValue);
  savaName(currentValue);
}

function askForName() {
  form.classList.add(SHWING_CN);
  form.addEventListener("submit", handleSubmit);
}

function paintGreeting(text) {
  form.classList.remove(SHWING_CN);
  greeting.classList.add(SHWING_CN);
  greeting.innerHTML = `Hello ${text}`;
}

function loadName() {
  const currentUser = localStorage.getItem(USERS_LS);
  if (currentUser === null) {
    //이름 적기 전
    askForName();
  } else {
    //이름 적음
    paintGreeting(currentUser);
  }
}

function init() {
  loadName();
  //로드네임 안적어서 여태 안나옴 개빡치게 ㅡㅡ
}

init();

 

 

 

todo.js
const toDoForm = document.querySelector(".js-toDoForm");
const toDoInput = toDoForm.querySelector("input");
//데이터 가져오는 곳
const toDoList = document.querySelector(".js-toDoList");
//데이터 출력하는 곳
const TODOS_LS = "toDos";

let toDos = [];
//const는 변화 불가

function deleteToDo(event) {
  console.log(event.target.parentNode);
  const btn = event.target;
  const li = btn.parentNode;
  toDoList.removeChild(li);
  //필터 기억
  const cleanToDos = toDos.filter(function (toDo) {
    // li.id 가 스트링 임..
    return toDo.id !== parseInt(li.id);
  });
  toDos = cleanToDos;
  savaToDos();
}

function savaToDos() {
  localStorage.setItem(TODOS_LS, JSON.stringify(toDos));
}

function paintToDo(text) {
  //console.log(text);
  const li = document.createElement("li");
  const delBtn = document.createElement("span");
  delBtn.innerText = "❌ ";
  delBtn.addEventListener("click", deleteToDo);
  const span = document.createElement("span");
  const newId = toDos.length + 1;
  span.innerText = text;
  li.appendChild(delBtn);
  li.appendChild(span);

  li.id = newId;

  toDoList.appendChild(li);

  const toDoObj = {
    text: text,
    id: newId,
  };

  toDos.push(toDoObj);
  savaToDos();
  //push 한 이후에 저장 해야됨 그전에 하면 null저장
}

function handleSubmit(event) {
  event.preventDefault();
  const currentValue = toDoInput.value;
  paintToDo(currentValue);
  toDoInput.value = "";
}

function loadToDos() {
  const loadedToDos = localStorage.getItem(TODOS_LS);
  if (loadedToDos !== null) {
    //console.log(loadedToDos);
    const parsedToDos = JSON.parse(loadedToDos);
    //console.log(parsedToDos);
    //포 이치 기억
    parsedToDos.forEach(function (toDo) {
      //console.log(toDo.text);
      paintToDo(toDo.text);
    });
    //포이치 안에 그대로 펑션을 넣음
  }
}

function init() {
  loadToDos();
  toDoForm.addEventListener("submit", handleSubmit);
}

init();

 

 

 

 

bg.js
const body = document.querySelector("body");

const IMG_NUMBER = 3;

function handleImageLoad() {
  console.log("finished loading");
}

function paintImage(imgNumber) {
  const image = new Image();
  image.src = `images/${imgNumber + 1}.jfif`;
  image.classList.add("bgImage");
  body.prepend(image);
  //image.addEventListener("loadend", handleImageLoad);
  //니코의 실수?
}

function genRandom() {
  const number = Math.floor(Math.random() * 6);
  return number;
}

function init() {
  const randomNumber = genRandom();
  paintImage(randomNumber);
}
init();

 

 

 

weather.js
const weather = document.querySelector(".js-weather");

const API_KEY = "회원가입후 발급 받은 내 키 입력 해야함";
const COORDS = "coords";

function getWeather(lat, lng) {
  fetch(
    `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
  )
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      const temperature = json.main.temp;
      const place = json.name;
      const aaa = json.weather[0].main;
      console.log(aaa);
      weather.innerText = `${aaa} / ${temperature} ℃  ${place}`;
    });
  //fetch()안에는 가져올 데이터가 들어가면됨 앞에 http 넣어주고 주의% 따옴표가 아닌 백틱 사용
}

function savaCoords(coordsObj) {
  localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}

function handleGeoSucces(position) {
  console.log(position.coords.latitude);
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  const coordsObj = {
    latitude: latitude,
    longitude: longitude,
    //latitude,longitude 로 작성 가능
  };
  savaCoords(coordsObj);
  getWeather(latitude, longitude);
}

function handleGeoError() {
  console.log("cant access geo locaion");
}

function askForCoords() {
  navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError);
  //위치 정보를 읽는 코드
}

function loadCoords() {
  const loadCoords = localStorage.getItem(COORDS);
  if (loadCoords === null) {
    askForCoords();
  } else {
    //getWeather
    const parsedCoords = JSON.parse(loadCoords);
    console.log(parsedCoords);
    getWeather(parsedCoords.latitude, parsedCoords.longitude);
  }
}

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

 

백그라운드 이미지는 unplash에서 다운 받았습니다.

unsplash.com/

 

Beautiful Free Images & Pictures | Unsplash

Beautiful, free images and photos that you can download and use for any project. Better than any royalty free or stock photos.

unsplash.com

 

직접 강의를 들으며 코드 작성하면 더 도움이 될거예요

 

728x90
반응형

댓글