[javascript] westagram 댓글 입력 기능

HyeLin·2021년 10월 20일
0
post-thumbnail

main.html

 <div class="post_container">
    <b>tosil_coton</b> 톰하디 사랑해
      <div class="post_time">56분전</div>
        <ul id="commentLists"></ul>
      </div>
      <div class="comment_container">
      	<input type="text" id="comment_input" placeholder="댓글 달기..." >
      	<button type="submit" id="comment_submit" disabled>게시</button>
      </div>
  </div>

main.js

"use strict";

const commentInput=document.getElementById("comment_input");
const commentButtonOn=document.getElementById("comment_submit");

function buttonOn(){
  if(commentInput.value.length>0){
    commentButtonOn.disabled = false;
  }else{
    commentButtonOn.disabled = true;
}
}
commentInput.addEventListener("input",buttonOn);

function checkInput(){
    if(commentInput.value.length>0){
        registerComment(commentInput.value);
    }
}
function registerComment(value){
const commentLists=document.getElementById("commentLists");
const newCommentList=document.createElement("li");
const newComment= `<span><span class="name"><b>shurc.onu</b>&nbsp</span>${value}</span><span class="delete">x</span>`;


newCommentList.innerHTML=newComment;
deleteComment(newCommentList);
commentLists.appendChild(newCommentList);

commentInput.value="";
}

function deleteComment(newCommentList){
    const deleteBtn= newCommentList.querySelector(".delete");
    deleteBtn.addEventListener("click", () =>{
        newCommentList.remove();
    })

}

const init = () =>{
    commentButtonOn.addEventListener("click",checkInput);
}

init();

댓글 기능 구현 풀이


먼저 어떻게 구현해야 할지 머리속으러 순서를 정리해보았다.
1. 댓글을 입력
2. 조건이 맞으면 게시 버튼 활성화
3. 게시버튼 클릭했을 때, 새로운 li 추가되면서 원래 입력했던 댓글 초기화
4. 댓글 게시 성공
5. x 버튼 누르면 댓글 지워지기


"use strict";

문법과 런타임 동작을 모두 검사하고, 실수를 에러로 변환, 변수 사용을 단순화 시켜준다. js는 오류를 어느정도 무시가 가능하다. 편하지만, 심각한 버그를 만들 수도 있다. strict모드가 이러한 실수를 에러로 변환해준다.

strict 모드에서 함수 선언은 최상위에서 선언해야 한다. 추후에 나올 js버젼을 쉽게 대응하기 위해!

const commentInput=document.getElementById("comment_input");
const commentButtonOn=document.getElementById("comment_submit");

먼저 댓글을 입력한 후, 버튼을 눌렀을 때 댓글이 게시가 되어야 하니까!
댓글 입력창(comment_input)과 댓글 게시 버튼(comment_submit) 값을 변수로 선언했다.

function buttonOn(){
  if(commentInput.value.length>0){
    commentButtonOn.disabled = false;
  }else{
    commentButtonOn.disabled = true;
}
}
commentInput.addEventListener("input",buttonOn);

댓글을 한글자라도 입력했을 때, '게시' 버튼이 활성화되는 함수를 선언했다.
만약 입력창의 값의 길이가 0보다 크면 disabled 되었던 버튼의 상태가 false로 변하며 활성화된다.

함수 선언 후, 입력창에 addEventListener를 통해 값이 "input"되었을 때, bottonOn 함수가 호출되도록 해주었다.

function registerComment(value){
const commentLists=document.getElementById("commentLists");
const newCommentList=document.createElement("li");
const newComment= `<span><span class="name"><b>shurc.onu</b>&nbsp</span>${value}</span><span class="delete">x</span>`;
  
newCommentList.innerHTML=newComment;
deleteComment(newCommentList);
commentLists.appendChild(newCommentList);

commentInput.value="";
}

댓글을 등록하는 함수를 만들어준다.
commentLists는 새로운 댓글이 담길 ul태그다. newCommentList에는 createElement를 통해 새로운 li태그를 만드는 값을 변수에 담아준다. newComment 변수에는 댓글이 달릴 형태를 만들어 넣어준다. ${value}는 매개변수 value의 값이며, 댓글의 내용이다. delete라는 함수 값 x는 곧 댓글을 지울 기능을 넣어줄 것이다...(구구절절...)

newCommentList은 innerHTML을 통해 newComment의 내용이 담긴 li태그가 담기며 생성된다.
밑에서 선언한 deleteComment함수를 통해 x버튼을 눌렀을 때, 게시되었던 댓글 삭제.
ul태그의 새로운 댓글의 li태그를 리스트 중 마지막 자식으로 붙여준다.

댓글이 게시가 된 후에도, 입력창에 댓글의 잔재가 남아있으면 안된다.
그렇기 떄문에 commentInput값을 "" 공백으로 만들어주며 초기화 시켜준다.

function checkInput(){
    if(commentInput.value.length>0){
        registerComment(commentInput.value);
    }
}

입력된 댓글 내용(commentInput.value)의 길이가 1글자 이상일 때, 댓글 등록 함수 registerComment에 댓글 내용을 넣어주는 함수.

function deleteComment(newCommentList){
    const deleteBtn= newCommentList.querySelector(".delete");
    deleteBtn.addEventListener("click", () =>{
        newCommentList.remove();
    })

}

댓글을 삭제하는 함수. 매개변수는 당연히 그렇듯 새로 생성된 댓글(newCommentList)이다. 댓글의 삭제(x)버튼을 클릭하였을 때, 댓글이 삭제되는 함수이다.

const init = () =>{
    commentButtonOn.addEventListener("click",checkInput);
}

init();

게시버튼을 클릭했을 떄, 값이 입력되는 함수.
ex) 댓글이 1글자 이상 입력되었을 때, 조건에 맞는지 체크를 한다. 조건에 맞으면 댓글을 게시하는 함수를 commentButtonOn함수에 addEventListener해준다.

init함수 호출하면 끝~~~

profile
개발자

0개의 댓글