본문 바로가기
🍀오늘도 삽질 중🍀/Javascript

댓글, 좋아요, 삭제 기능 구현하기

by 매진2 2023. 6. 13.
728x90

main 페이지에서 처음으로 자바스크립트 활용한 과제이다.

4번과 6번이 연관이 있어서 한번에 진행했다.


<mission 4. 댓글 내용 입력 후 Enter press, 혹은 게시 버튼 클릭 시 댓글 추가 기능>

댓글 입력 후 엔터키를 누르거나 게시 버튼 클릭 시 댓글이 추가될 수 있도록 구현해주세요.

<mission 6. 댓글 좋아요 / 삭제 기능>

댓글 마다 좋아요, 삭제 버튼을 추가해 버튼을 누를 시 각각의 기능이 실행되도록 구현해주세요.


먼저 필요한 값들을 DOM으로 불러왔다.

ID값은 전체 파일 중 1개라 불러내면 1개만 나오지만

class는 여러개일 수도 있어서 배열로 나오기때문에 index를 적어줘야한다.

const inputComment = document.getElementById("input");
const buttonComment = document.getElementById("button");
const newComment = document.getElementById("newComment");
const commentForm = document.getElementsByClassName("comment")[0];

input의 value 값을 변수로 선언해주고

if문의 조건으로 input의 value 값이 하나라도 생겼을 때 버튼 색이 바뀌도록 함수를 짜주었다.

그리고 input에 keyup 이벤트가 생겼을 때 함수가 작동하도록 해주었다.

function responseBtn() {
  const inputValue = inputComment.value;

  if (inputValue.length > 0) {
    buttonComment.style.color = "blue";
    buttonComment.disabled = false;
  } else {
    buttonComment.style.color = "#cbe0f9";
    buttonComment.disabled = true;
  }
  return;
}

inputComment.addEventListener("keyup", responseBtn);


버튼을 활성화했으니 이제 댓글 기능을 하는 addComment 함수를 짜주기로 하자.

먼저 댓글 관련한 값들이 들어갈 수 있도록 createElement로 

전체 태그가 들어갈 컨테이너용 div 태그를 만들어주고 ID와 댓글이 들어갈 span 태그, 좋아요, 삭제 버튼을 생성해주었다.

function addComment(e) {

  const comment = document.createElement("div");
  const userID = document.createElement("span");
  const commentText = document.createElement("span");
  const likeBtn = document.createElement("button");
  const deletBtn = document.createElement("button");

그리고 각 태그에 class를 생성했다.

  comment.classList.add("comentClass");
  userID.classList.add("userIDClass");
  commentText.classList.add("commentTextClass");
  likeBtn.classList.add("likeBtnClass");
  deletBtn.classList.add("deletBtnClass");

ID는 고정값으로 넣어주었고 댓글이 들어갈 span 태그에 input.value 값을 넣어준다.

  userID.innerHTML = "wecode "
  commentText.innerHTML = inputComment.value;

마지막으로 html에서 만들었던 div 태그에 아까 생성한 컨테이너용 div 태그를 넣어주고

나머지 span, button 태그들을 아까 생성한 컨테이너용 div 태그에 넣어준다.

  newComment.appendChild(comment);
  comment.appendChild(userID);
  comment.appendChild(commentText);
  comment.appendChild(likeBtn);
  comment.appendChild(deletBtn);

 댓글이 올라가고 나면 다시 댓글창이 처음으로 돌아올 수 있도록

input.value의 값을 비워주고 버튼 색을 비활성화 시켜준다.

  inputComment.value = "";
  buttonComment.style.color = "#cbe0f9";
  buttonComment.disabled = true;

그리고 이벤트를 넣어주었다.

buttonComment.addEventListener("click", addComment);

댓글을 쓰는 곳은 input인데 반응은 button이 해야해서 포커스가 button에 있거나 버튼에 클릭을 해주어야만 페이지가 이동해서

멘토님께 여쭤봤더니 form 태그를 알려주셨다.

html에서 div 태그 대신 form 태그를 써보라고 하셨다.

<form class="comment">
  <input id="input" placeholder="댓글 달기..." />
  <button id="button">게시</button>
</form>

그리고 form태그가 default 값이 새로고침이라서 새로고침이 아닌 원하는 기능이 작동하도록 함수를 하나 넣어주셨다.

  e.preventDefault();

이제 댓글에 좋아요 버튼과 댓글 삭제 버튼을 추가해보자.

먼저 좋아요 버튼을 누르면 빈 하트가 빨간하트로 변하게 만들고 싶었다.

그래서 찾은 방법은 class를 빈하트와 빨간하트로 나누어 버튼을 누르면 클래스가 바뀌도록 적용해보았다.

 초기 세팅은 빈하트지만 빈하트로 시작하면 첫 클릭이 먹히지 않아서 시작을 빨간하트로 했다.

function likechange(e) {
  let target = e.target.classList;

  if (target.contains("redheart")) {
    target.remove("redheart");
    target.add("likebtnClass");
  } else {
    target.remove("likebtnClass");
    target.add("redheart");
  }
}
 likeBtn.addEventListener("click", likechange);

삭제버튼은 만들어둔 컨테이너용 div태그를 지우는 방법으로 진행했다.

  function commentDelet() {
    comment.remove("comment");
  }
  
  deletBtn.addEventListener("click", commentDelet);

아래는 전체 코드이다.

addEventListener는 순서에 덜 구애 받아

responseBtn 함수가 위치에 따라 함수가 작동할때도 있고 안할때도 있어서 맨 위에 배치했다.

const inputComment = document.getElementById("input");
const buttonComment = document.getElementById("button");
const newComment = document.getElementById("newComment");
const commentForm = document.getElementsByClassName("comment")[0];

inputComment.addEventListener("keyup", responseBtn);

function responseBtn() {
  const inputValue = inputComment.value;
  
  if (inputValue.length > 0) {
    buttonComment.style.color = "blue";
    buttonComment.disabled = false;
  } else {
    buttonComment.style.color = "#cbe0f9";
    buttonComment.disabled = true;
  }
  return;
}

function addComment(e) {

  const comment = document.createElement("div");
  const userID = document.createElement("span");
  const commentText = document.createElement("span");
  const likeBtn = document.createElement("button");
  const deletBtn = document.createElement("button");

  e.preventDefault();

  comment.classList.add("comentClass");
  userID.classList.add("userIDClass");
  commentText.classList.add("commentTextClass");
  likeBtn.classList.add("likeBtnClass");
  deletBtn.classList.add("deletBtnClass");

  userID.innerHTML = "wecode ";
  commentText.innerHTML = inputComment.value;

  newComment.appendChild(comment);
  comment.appendChild(userID);
  comment.appendChild(commentText);
  comment.appendChild(likeBtn);
  comment.appendChild(deletBtn);

  inputComment.value = "";
  buttonComment.style.color = "#cbe0f9";
  buttonComment.disabled = true;

  //comment 변수 쓰기 위에 addComment 함수 안에 배치
  function commentDelet() {
    comment.remove("comment");
  }

  //likeBtn, deletBtn 사용 위에 함수 안에 배치
  likeBtn.addEventListener("click", likechange);
  deletBtn.addEventListener("click", commentDelet);
}

buttonComment.addEventListener("click", addComment);

function likechange(e) {
  let target = e.target.classList;

  if (target.contains("redheart")) {
    target.remove("redheart");
    target.add("likebtnClass");
  } else {
    target.remove("likebtnClass");
    target.add("redheart");
  }
}
728x90