당근먹는하니
귀엽고 행복해
당근먹는하니
전체 방문자
오늘
어제
  • 분류 전체보기 (274)
    • 다람쥐🐿 (26)
    • C++ 공부빵야 (7)
    • 공부👻 (5)
    • 프론트엔드✏️ (228)
      • 코드캠프 (120)
      • 팀 프로젝트✨ (31)
      • 개인공부 (67)
    • 프론트엔드 - 바닐라js (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 팀 프로젝트
  • 공통 컴포넌트
  • graphql
  • JS
  • 프로그래머스
  • typescript
  • 팀프로젝트
  • next.js
  • 리액트
  • 부트캠프
  • refreshtoken
  • 코드캠프
  • 알고리즘
  • 자바스크립트
  • 코딩
  • algorithm
  • 회고
  • 코딩 부트캠프
  • CSS
  • 팀플
  • HTML
  • 배포
  • React-hook-form
  • javascrpit
  • react
  • emotion
  • 배열
  • ssg
  • javascript
  • 프론트엔드

최근 댓글

최근 글

티스토리

250x250
반응형
hELLO · Designed By 정상우.
당근먹는하니

귀엽고 행복해

[javascript] 바닐라 JS로 크롬 앱 만들기 - 오늘의 기분 선택하기, 디데이까지~
프론트엔드 - 바닐라js

[javascript] 바닐라 JS로 크롬 앱 만들기 - 오늘의 기분 선택하기, 디데이까지~

2022. 10. 6. 14:08
728x90
반응형
// index.html
<ul class="mood">
      <li>뒹굴뒹굴</li>
      <li>스트레스</li>
      <li>라라라라</li>
    </ul>
    
// mood.js

const moods = document.querySelectorAll(".mood li");
const moodImg = document.querySelector("#mood-img");

console.log(moods);

const todayMood = ["뒹굴뒹굴", "스트레스", "라라라라"];

const onClickMood = (event) => {
  todayMood.map((image) => {
    switch (event.target.innerText) {
      case image:
        moodImg.src = `img/${image}.gif`;
        return;

      default:
        return;
    }
  });
};

moods.forEach((mood) => mood.addEventListener("click", onClickMood));

 뒹굴뒹굴 누르면 뒹굴거리는 모코코, 스트레스 누르면 매운 거 먹는 모코코, 라라라라 누르면 이디야 모코코가 나온다. 

새로운..바닐라 JS! 그리고 오랜만에 보는 switch문... 처음 써보는 forEach(왜 map으로는 이벤트리스너가 안 뜨는지 모르겠다.)

 

 이렇게도 되긴하는데 뒹굴뒹굴, 스트레스, 라라라라 를 html이랑 javascript 양쪽에서 두 번 쓰는 게 비효율적이라고 느껴졌다. 

 

 // index.html
 <ul class="mood-ul">
    </ul>
    
    
// mood.js

const moodUl = document.querySelector(".mood-ul");
const moodImg = document.querySelector("#mood-img");

const todayMoods = ["뒹굴뒹굴", "스트레스", "라라라라"];

todayMoods.map((mood) => {
  const todayMood = document.createElement("div");
  todayMood.className = "mood";
  todayMood.innerText = mood;
  moodUl.appendChild(todayMood);
});

const moods = document.querySelectorAll(".mood");


const onClickMood = (event) => {
  todayMoods.map((image) => {
    switch (event.target.innerText) {
      case image:
        moodImg.src = `img/${image}.gif`;
        return;

      default:
        return;
    }
  });
};

moods.forEach((mood) => mood.addEventListener("click", onClickMood));

중간에 const moods = 들어가 있는 게 좀 불편하다..ㅎ

mood 클래스의 div를 만든 뒤에 가져와야 하기 때문에 순서가 이렇게 됐다. (뭐가 맞는진 모른다~~~!)

 

이제 또 다른 기분을 추가할 때, 이미지 폴더에 이미지 넣고 맨 위의 배열에 추가만 해주면 된다. 

 

근데 진짜 이게 맞는진 모르겠다. (좋은 방법인지는 모르겠다!)

 

 

 


 

 

내 생일까지 < 하드 코딩된 부분을 바꿔보자

 

 

<form id="count-form">
          <input id="until-input" class="hidden"/>
          <span id="until">까지</span>
        </form>

greeting 만들었던 것처럼 hidden을 쓰기로 했다. 

// .js

const until = document.querySelector("#until");
const untilInput = document.querySelector("#until-input");
const countForm = document.querySelector("#count-form");

const getUntil = () => {
  const localUntil = localStorage.getItem("until");
  return localUntil;
};

until.innerText = getUntil() || "디데이까지";
untilInput.defaultValue = getUntil() || "디데이까지";

const onClickUntil = () => {
  until.classList.add(HIDDEN_CLASS);

  untilInput.classList.remove(HIDDEN_CLASS);
};

until.addEventListener("click", onClickUntil);

const handleUntilSubmit = (event) => {
  event.preventDefault();
  localStorage.setItem("until", untilInput.value);
  untilInput.value = "";
  if (getUntil()) {
    until.innerText = `${getUntil()}`;
  }
  untilInput.classList.add(HIDDEN_CLASS);
  until.classList.remove(HIDDEN_CLASS);
};

countForm.addEventListener("submit", handleUntilSubmit);

 

뭔가 굉장히 코드가 지저분해졌다. 

안돼서 이것저것 시도하다보니... ^^??라기엔 greeting과 많이 다르지 않은 것 같은데 왜 이렇게까지 된거지? 

 

react 가 굉장히 그리웠다. 

그리고 HIDDEN_CLASS를 다시 선언해야하는 줄 알았는데 다른 js파일의 것도 사용할 수 있었다! 

 

728x90
반응형
저작자표시 비영리 동일조건 (새창열림)

'프론트엔드 - 바닐라js' 카테고리의 다른 글

... spread 연산자  (0) 2022.12.29
[javascript] 바닐라 JS로 크롬 앱 만들기 - 끝  (0) 2022.10.11
[javascript] 바닐라 JS로 크롬 앱 만들기 - #7.1 ~ toDo list  (0) 2022.10.06
[javascript] 바닐라 JS로 크롬 앱 만들기 - 디데이 숙제  (0) 2022.10.05
[javascript] 바닐라 JS로 크롬 앱 만들기 #3.0 - #3.4  (0) 2022.09.21
    '프론트엔드 - 바닐라js' 카테고리의 다른 글
    • ... spread 연산자
    • [javascript] 바닐라 JS로 크롬 앱 만들기 - 끝
    • [javascript] 바닐라 JS로 크롬 앱 만들기 - #7.1 ~ toDo list
    • [javascript] 바닐라 JS로 크롬 앱 만들기 - 디데이 숙제
    당근먹는하니
    당근먹는하니

    티스토리툴바