TIL - Instagram clone coding - 댓글 창 구현하기

김현재·2021년 8월 11일
2

구현 내역

  1. input에 값이 들어오면 Post 버튼 활성화
  2. input에 값이 있을 때 post버튼을 클릭하거나 enter키를 누르면 댓글 게시하기 (게시된 것 처럼 보이게 하기)
  3. input 값이 비어있을 때 댓글이 게시되지 않도록 하기



1. input 값이 들어오면 Post 버튼 활성화

HTML

<div class="commentForm content-box">
	<button class="icon emoji" type="button"></button>
	<input type="text" class="commentInput" placeholder="Add a comment...">
	<button type="button" class="Btn inactive commentPost">Post</button>
</div>

Javascript

const commentForm = document.querySelector(".commentForm");
 
commentForm.addEventListener("keyup",() => {
    const commentInput = document.querySelector(".commentInput").value;
    const commentBtn = document.querySelector(".commentPost");

    commentInput.length > 0 
        ? commentBtn.classList.remove("inactive") 
        : commentBtn.classList.add("inactive");
    
})

input 요소를 모두 감싸고 있는 부모요소인 commentForm 에다 addEventListener 를 걸어 이벤트를 받아오도록 지정했다.

Event bubbling 효과를 활용해 필요한 자녀 요소들도 모두 이벤트를 받아올 수 있도록 했다.

input에 들어온 값(value)가 있을 때, 즉 0 이상일 때 post 버튼이 활성화가 되어야 하기에, 기존에 지정되어있던 inactive 클래스를 제거하도록 하였다.

물론, backspace를 사용하여 다시 값을 0으로 만들었을 때는 inactive 클래스를 생성해서 버튼이 활성화 되지 못하도록 했다.



2. input에 값이 있을 때 post버튼을 클릭하거나 enter키를 누르면 댓글 게시

let replies = document.querySelector(".replies"); // ul
let postBtn = document.querySelector(".commentPost"); // submit btn
let currentValue = commentInput.value;  //  입력 값

const commentInput = document.querySelector(".commentInput"); //  input

function onAdd() {
    createItem(currentValue);
    currentValue = "";
}

function createItem(text) {
    const reply = document.createElement("li");
    reply.setAttribute("class", "reply");
    reply.innerHTML = 
        `<div class="replyDetail">
            <a href="#" class="userID">hyun___jjae</a>
            <a href="#" class="comment">${text}</a>
        </div>
        <span class="icon heartBtn small_icon"></span>`  

    // 화면에 보이게
    replies.appendChild(reply);
}
  1. onAdd() 함수는 input에 들어오는 입력값을 createItem 에 전달 후 초기화 시키는 역할을 담당하도록 했다.

  2. createItem() 함수는 입력 값을 받으면 그 입력값을 반영한 li 요소를 생성해내도록 구현했다.

    innerHTMLsetAttribute 를 사용해 기존 li 요소들과 양식을 맞추도록 했고, 만들어낸 요소를 HTML에 연결시켜야 하기에, 부모 요소가 될 replies 라는 클래스를 가진 ulappendChild 를 활용해서 묶어줬다.



3. input 값이 비어있을 때 댓글이 게시되지 않도록 하기

function init() {
    postBtn.addEventListener("click", () => {
        if(currentValue > 0) {
            onAdd();
        }
    });
    commentInput.addEventListener("keydown", (e) => {
        if(e.key === "Enter") {
            if(currentValue > 0) {
                onAdd();
            }
        }
    });
};

postBtn, commentInput 모두 이벤트 발생 시 현재 입력값이 0보다 클 경우에만 onAdd() 함수를 실행하도록 조건문을 걸어 값이 빈 경우 댓글 추가가 되는 것을 제한하였다.



같이 보면 좋을 내용

profile
쉽게만 살아가면 재미없어 빙고!

0개의 댓글