[유데미x스나이퍼팩토리] 10주 완성 프로젝트 캠프 7일차 - JavaScript 학습

강경서·2023년 6월 20일
0
post-thumbnail

🔎 BOM vs DOM


BOM이란?

  • BOM(Browser Object Model)은 웹 브라우저와 관련된 객체를 다루는 모델을 의미합니다.
  • 브라우저 창, 프레임, 히스토리, 쿠키 등과 같은 브라우저와 관련된 객체를 다루는 모델입니다.
  • window 객체를 중심으로 다양한 객체를 포함합니다. 예를 들어, navigator, location, history, screen등을 포함합니다.
  • 브라우저와의 상호작용을 통해 브라우저 창 조작, 페이지 이동, 쿠키 설정 등과 같은 브라우저 관련 작업을 수행합니다.
  • 표준화된 API가 없으며, 브라우저마다 구현이 다를 수 있습니다.

DOM이란?

  • DOM(Document Object Model)은 HTML 문서의 요소들을 다루는 모델을 의미합니다.
  • HTML 문서의 구조, 요소, 속성 등을 다루는 모델입니다.
  • document 객체를 중심으로 HTML 문서의 요소와 관련된 객체들을 포함합니다. 예를 들어, element, attribute, text등을 포함합니다.
  • HTML 문서의 요소를 조작하고 변경함으로써 웹 페이지의 동적인 표시와 상호작용을 가능케 합니다.
  • W3C에서 표준화된 API를 정의하고 있어서 대부분의 브라우저에서 동일하게 동작합니다.

🍪 쿠키 vs 캐시


쿠키란?

  • 쿠키는 클라이언트(브라우저)에 저장되는 작은 데이터 조각입니다.
  • 서버에서 클라이언트로 전송되어 브라우저에 저장되며, 이후에 같은 서버에 요청할 때마다 클라이언트에서 서버로 전송됩니다.
  • 주로 사용자 인증, 세션 관리, 개인화 등을 위해 사용됩니다.
  • 유효 기간을 설정하여 일정 기간 동안 유지될 수 있습니다.
  • 클라이언트에서 수정이 가능하며, JavaScript를 사용하여 조작할 수 있습니다.

캐시란?

  • 캐시는 웹 페이지, 이미지, 스크립트 등의 리소스를 저장하는 임시 저장소입니다.
  • 웹 페이지를 요청할 때 브라우저는 해당 페이지의 리소스를 서버에서 다룬로드하여 캐시에 저장합니다.
  • 같은 페이지에 다시 접근할 때 브라우저는 캐시된 리소스를 사용하여 서버에 다시 요청하지 않고 페이지를 빠르게 로드합니다.
  • 웹 페이지의 로딩 속도를 향상시키고 네트워크 트래픽을 줄이는 데 도움이 됩니다.
  • 브라우저에서 관리되며, 일정 시간이 지나면 자동으로 만료되어 새로운 버전의 리소스를 가져옵니다.
  • 클라이언트에서는 캐시의 내용을 직접 수정할 수 없습니다.

🚀 팀 실습

장바구니 카트 만들기

Github 링크

  • index.html
  <body>
    <ul class="food__list">
      <li class="food__list__box" id="1">
        <span>광어</span>
        <span>20,000원</span>
        <button>장바구니에 추가</button>
      </li>
      <li class="food__list__box" id="2">
        <span>우럭</span>
        <span>21,000원</span>
        <button>장바구니에 추가</button>
      </li>
      <li class="food__list__box" id="3">
        <span>연어</span>
        <span>21,000원</span>
        <button>장바구니에 추가</button>
      </li>
      <li class="food__list__box" id="4">
        <span>참돔</span>
        <span>30,000원</span>
        <button>장바구니에 추가</button>
      </li>
    </ul>
    <div class="cart">
      <h1>장바구니</h1>
      <ul class="cart__list"></ul>
    </div>
  </body>

메뉴 리스트와 장바구니 카트를 만들어 주었습니다. document 객체의 querySelectorAll 메서드를 사용하기 위해 메뉴 리스트의 class이름을 동일하게 설정하였습니다.


  • script.js
const cartBtns = document.querySelectorAll(".food__list__box button");
const cartList = document.querySelector(".cart__list");

const printFood = (name, price) => {
  const cartListBox = document.createElement("li");
  const countBox = document.createElement("span");
  cartListBox.innerText = `${name} - ${price}`;
  countBox.innerText = "1개";
  cartListBox.append(countBox);
  cartList.append(cartListBox);
};

const addFood = (event) => {
  const {
    target: { parentNode },
  } = event;
  const foodName = parentNode.children[0].textContent;
  const foodPrice = parentNode.children[1].textContent;
  printFood(foodName, foodPrice);
};

cartBtns.forEach((btn) => btn.addEventListener("click", addFood));

querySelectorAll 메서드들 사용하여 메뉴 리스트의 버튼들은 전부 선언하였습니다. 그리고 해당 버튼들을 forEach 메서드를 이용하여 각각의 버튼에게 addEventListener를 통해 click 이벤트가 발생할 경우 addFood 함수를 실행시키게 하였습니다. addFood 함수는 클릭한 버튼의 event를 받아옵니다. 해당 event를 통해 previousElementSibling, parentNode등을 통해 부모 요소 및 주변 요소들을 선택할 수 있습니다. 이를 통해 메뉴의 이름과 가격이 적힌 태그들의 text요소를 textContent를 통해 값을 가져올 수 있습니다. 그 후 document 객체의 createElement 메서드를 이용하여 새로운 태그들을 생성한 후 원하는 text들 적어 append를 통해 자식 태그들로 부여할 수 있습니다.

previousElementSibling : 동등한 관계의 이전 태그를 의미
parentNode : 부모 노드를 의미


const cartBtns = document.querySelectorAll(".food__list__box button");
const cartList = document.querySelector(".cart__list");

const printFood = (name, price, id) => {
  const cartListBox = document.createElement("li");
  const countBox = document.createElement("span");
  cartListBox.innerText = `${name} - ${price}`;
  countBox.innerText = "1개";
  cartListBox.append(countBox);
  cartListBox.id = `list${id}`;
  cartList.append(cartListBox);
};

const addFood = (event) => {
  const {
    target: { parentNode },
  } = event;

  const cartListBoxs = document.querySelectorAll(".cart__list li");
  const idArray = [];

  cartListBoxs.forEach((box) => {
    if (`list${parentNode.id}` === box.id) {
      idArray.push(box.id);
    }
  });

  const exist = idArray.includes(`list${parentNode.id}`);

  if (exist) {
    cartListBoxs.forEach((box) => {
      if (`list${parentNode.id}` === box.id) {
        const count = +box.children[0].textContent.substring(
          0,
          box.children[0].textContent.length - 1
        );
        box.children[0].innerText = `${count + 1}`;
      }
    });
  } else {
    const foodName = parentNode.children[0].textContent;
    const foodPrice = parentNode.children[1].textContent;
    printFood(foodName, foodPrice, parentNode.id);
  }
};

cartBtns.forEach((btn) => btn.addEventListener("click", addFood));

위의 코드는 카트에 담길 메뉴들의 태그에 id값을 부여하여 중복된 메뉴들 선택할시 이미 선택된 메뉴들의 태그의 내용을 변경해주는 코드입니다. forEach를 통해 중복된 id값을 찾는데 활용하였고, substring를 이용하여 string 값을 필요한 부분만 선택하여 수정할 수 있었습니다.


장바구니 카트 만들기 결과


실시간 채팅 만들기

Github 링크

  • index.html
 <body>
    <header>
      <h1>실시간 채팅</h1>
    </header>
    <div class="chat"></div>
    <form id="user">
      <input type="text" id="user__name" placeholder="사용자명" />
      <input type="text" id="user__msg" placeholder="메세지를 입력하세요." />
      <input type="submit" value="전송" id="user__submit" />
    </form>
  </body>

채팅 사용자명과 메세지 내용을 적을 input 태그와 만들어질 채팅들을 담을 태그를 만들어 주었습니다.


  • script.js
const userForm = document.querySelector("#user");
const nameInput = document.querySelector("#user__name");
const msgInput = document.querySelector("#user__msg");
const submitBtn = document.querySelector("#user__submit");
const chat = document.querySelector(".chat");

const printMsg = (name, msg) => {
  const newChat = document.createElement("div");
  const newChatName = document.createElement("span");
  const newChatMsg = document.createElement("span");
  newChatName.innerText = `${name}: `;
  newChatName.className = "chat__box__name";
  newChatMsg.innerText = msg;
  newChatMsg.className = "chat__box__msg";
  newChat.appendChild(newChatName);
  newChat.appendChild(newChatMsg);
  chat.appendChild(newChat);
};

const addMsg = (event) => {
  event.preventDefault();
  const userName = nameInput.value;
  const userMsg = msgInput.value;
  printMsg(userName, userMsg);
  msgInput.value = "";
};

userForm.addEventListener("submit", addMsg);

input들이 담긴 form에게 addEventListener 이용하여 submit 이벤트 발생시 addMsg 함수를 실행시키게 만들었습니다. 이때 form은 기본적으로 submit이 실행시 페이지의 reload가 발생되므로 preventDefault를 이용하여 해당 reload를 막아주어야 합니다. 그 후 document 객체의 createElement 메서드를 이용하여 새로운 태그들을 생성한 후, 사용자명과 메세지 내용을 적는 input들의 value를 담아 append를 통해 자식 태그들로 부여할 수 있습니다.


실시간 채팅 만들기 결과


할 일 목록 만들기

Github 링크

  • index.html
  <body>
    <form class="todo__form">
      <input
        type="text"
        class="todo__form__input"
        placeholder="할 일을 입력하세요."
        required
      />
      <input type="submit" value="Add" class="todo__form__submit" />
    </form>
    <ul class="todo__list"></ul>
  </body>

할 일의 내용을 적을 input 태그와 목록을 담을 태그를 만들어 주었습니다.


  • script.js
const todoForm = document.querySelector(".todo__form");
const todoInput = todoForm.querySelector(".todo__form__input");
const todoSubmit = todoForm.querySelector(".todo__form__submit");
const todoList = document.querySelector(".todo__list");

const deleteTodo = (event) => {
  const {
    target: { parentNode },
  } = event;
  parentNode.remove();
};

const printTodo = (content, id) => {
  const newTodo = document.createElement("li");
  const newTodoContent = document.createElement("span");
  const deleteBtn = document.createElement("button");
  newTodoContent.innerText = content;
  deleteBtn.innerText = "Delete";
  deleteBtn.addEventListener("click", deleteTodo);
  newTodo.id = id;
  newTodo.appendChild(newTodoContent);
  newTodo.appendChild(deleteBtn);
  todoList.appendChild(newTodo);
};

const addTodo = (event) => {
  event.preventDefault();
  const todoContent = todoInput.value;
  const todoId = Date.now();
  printTodo(todoContent, todoId);
  todoInput.value = "";
};

todoForm.addEventListener("submit", addTodo);

createElement 메소드를 통해 만들어진 button 태그에 addEventListener를 적용시킬 수 있습니다. 또한 remove를 통해 HTMl문서의 원하는 태그들을 삭제할 수 있습니다.


할 일 목록 만들기 결과


📝후기

바닐라 Javascript를 이해할 수 있는 좋은 시간이었습니다. 많은 실습을 통해 HTMl 문서의 요소들을 통제하는 데 익숙해질 수 있었습니다. 다만 아직은 Javascript를 통해 객체 및 배열을 다루는 데에는 부족함이 느껴졌습니다. 더 많은 실습과 프로젝트들을 통해 자유롭게 Javascript를 사용하고 싶다는 생각이 들었습니다.



본 후기는 유데미-스나이퍼팩토리 10주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.

#프로젝트캠프 #프로젝트캠프후기 #유데미 #스나이퍼팩토리 #웅진씽크빅 #인사이드아웃 #IT개발캠프 #개발자부트캠프 #리액트 #react #부트캠프 #리액트캠프

profile
기록하고 배우고 시도하고

0개의 댓글