[westagram]댓글 내용 입력 후 Enter press, 혹은 게시 버튼 클릭 시 댓글 추가 기능

이해용·2022년 5월 7일
0
post-thumbnail

구상

처음 댓글을 달고 Enter press 또는 게시 버튼을 클릭 했을 때 42분전이라고 기재되어있는 곳 위에 댓글이 생성되기를 원했다. 처음 댓글로 css구현했을 때 div tag를 사용했으나 form tag를 사용해야 배웠던 내용을 사용할 수 있다고 하여 form tag를 사용했다.

  1. 댓글 작성 후 enter 또는 '게시'글 클릭시 댓글 생성
  2. 작성된 댓글 오른쪽에 댓글을 삭제할 수 있는 x표시 생성
  3. 작성된 댓글 style 주기

1. 선언

선언

const toDoForm = document.getElementById("comment");
const toDoInput = document.querySelector("#comment input");
const toDoList = document.getElementById("todo-list");

console.log() 확인

console.log(toDoForm); =>
<form id="comment">
  <i class="fa-regular fa-face-smile fa-lg"></i>
  <input type="text" placeholder="댓글 달기..." required/>
  <button type="button">게시</button>
</form> 

console.log(toDoInput); =>
<input type="text" placeholder="댓글 달기..." required/>
  
console.log(toDoList); => 
<ul id="todo-list"></ul>

2. 함수 선언 및 addEventListener 선언

Event.preventDefault()

Event 인터페이스preventDefault() 메서드는 어떤 이벤트를 명시적으로 처리하지 않은 경우, 해당 이벤트에 대한 사용자 에이전트의 기본 동작을 실행하지 않도록 지정합니다.
댓글을 기재하고 엔터를 누르면 새로운 창이 열리게 되므로 event.preventDefault(); 를 기재해줘야 새로운 창이 나타나지 않습니다.

HTMLFormElement: submit event

submit 이벤트는 <form>이 제출될 때 발생합니다.
<form> 형식 안에서 input 태그에 댓글을 작성하면 submit 되어 요청한 형식을 제출하게 됩니다.

function handleToDoSubmit(event) {
  event.preventDefault();
  const newToDo = toDoInput.value;
  toDoInput.value = "";
  paintToDo(newToDo); // 이후 선언할 함수에 newToDo 를 넣어줌
}

toDoForm.addEventListener("submit", handleToDoSubmit);

console.log(newToDo) 결과 사진


3. 새로운 함수에 li tag, span tag, button tag 생성

함수 내에서 새로운 tag를 만드는 함수 createElement method 를 이용하여 li, span, button tag를 생성해주고 appendChild method 를 이용하여 span과 button은 li tag의 자식 요소로, li tag는 toDoList의 자식 요소로 선언해준다.
innerText 속성을 이용하여 함수 내에 넣어 줄 수 있도록 댓글을 달면 화면에 나타날 수 있도록 선언해준다.

function paintToDo(newToDo) {
  const li = document.createElement("li");//화면에 나타야할 순서대로 작성해준다.
  const span = document.createElement("span");
  span.innerText = newToDo;
  const button = document.createElement("button");
  button.innerText = "x";
  li.appendChild(span);
  li.appendChild(button);
  toDoList.appendChild(li);
}

4. 댓글 삭제 기능 추가

현재 구현한 내용으로는 x버튼을 누른다고 하여 댓글이 삭제 되지 않는다.
댓글 삭제를 위해서는 새로운 함수를 선언해야 한다.

target 속성을 이용하여 생성된 댓글만 선택하여 사라질 수 있도록 target을 지정해준다.
parentElement 속성은 해당 위치의 부모 요소를 지정해주는 속성이다.
따라서, const li = event.target.parentElement; 는 함수 내 li 이름을 가진 값은 현재 위치의 부모요소를 선택해준다는 뜻이다.
li.remove(); 는 위에 선택된 타겟의 부모요소를 삭제해준다는 뜻이다.

function deleteToDo(event) {
  const li = event.target.parentElement;
  li.remove();
}

5. 이름 추가하기

실제 사이트라면 배열에서 추가를 하겠지만 기능을 비슷하게 하는 것이 목적이므로 paintToDo(newToDo) 함수 내에서 아이디 text를 추가하여 진행했다.

function paintToDo(newToDo) {
  const li = document.createElement("li");
  const span1 = document.createElement("span");
  span1.innerText = "hey.yong44";
  const span2 = document.createElement("span");
  span2.innerText = newToDo;
  const button = document.createElement("button");
  button.innerText = "x";
  button.addEventListener("click", deleteToDo);
  li.appendChild(span1);
  li.appendChild(span2);
  li.appendChild(button);
  toDoList.appendChild(li);
}

6. '게시' 버튼 클릭으로 댓글 구현

'게시' button을 클릭하여도 댓글을 구현할 수 있도록 진행하기 위해 먼저 btn이라는 함수를 선언해준다.

const btn = document.querySelector("#comment button");

console.log(btn);
=> <button type="button">게시</button>

addEventListener 를 사용하여 type을 click 으로 설정해주고 함수명을 넣어줍니다.

btn.addEventListener("click", handleToDoSubmit);

위의 click 이벤트는 포인팅 디바이스 버튼(일반적으로 마우스 기본 버튼)이 하나의 요소(엘리먼트)에서 눌려지고 놓을 때 시작합니다.

style 추가

실제와 비슷하게 구현하기 위해 css 파일에 style을 추가하여 진행합니다.

css

#todo-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

#todo-list > li {
  display: flex;
}

#todo-list > li > span:nth-child(1) {  
  flex-grow: 0.3;
  font-weight: bold;
}

#todo-list > li > span:nth-child(2) {  
  flex-grow: 10;
}

#todo-list > li > button {
  color: gray;
  background-color: white;  
  border: none;
  flex-grow: 0.1;
}

최종 구현 코드

style을 추가하였기 때문에 해당되는 내용으로 function paintToDo(newToDo) 함수를 변경하여 취합합니다.

const toDoForm = document.getElementById("comment");
const toDoInput = document.querySelector("#comment input");
const btn = document.querySelector("#comment button");
const toDoList = document.getElementById("todo-list");

function deleteToDo(event) {
  const li = event.target.parentElement;
  li.remove();
}

function paintToDo(newToDo) {
  const li = document.createElement("li");
  const span1 = document.createElement("span");
  span1.innerText = "hey.yong44";
  const span2 = document.createElement("span");
  span2.innerText = newToDo;
  const button = document.createElement("button");
  button.innerText = "x";
  button.addEventListener("click", deleteToDo);
  li.appendChild(span1);
  li.appendChild(span2);
  li.appendChild(button);
  toDoList.appendChild(li);
}

function handleToDoSubmit(event) {
  event.preventDefault();
  const newToDo = toDoInput.value;
  toDoInput.value = "";
  paintToDo(newToDo);
}

toDoForm.addEventListener("submit", handleToDoSubmit);
btn.addEventListener("click", handleToDoSubmit);

출처 및 참고
유튜브 노마드 코더 강의
https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault
https://developer.mozilla.org/ko/docs/Web/Events
https://developer.mozilla.org/ko/docs/Web/API/Element/click_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
https://developer.mozilla.org/ko/docs/Web/API/Document/createElement
https://developer.mozilla.org/ko/docs/Web/API/Node/appendChild
https://developer.mozilla.org/ko/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/ko/docs/Web/API/Event/target
https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
https://developer.mozilla.org/en-US/docs/Web/API/Element/remove

profile
프론트엔드 개발자입니다.

0개의 댓글