[JS] 댓글 기능 구현 (westagram)

에릭리·2022년 6월 30일
1

wecode

목록 보기
2/4

필수 구현 사항:

  1. 로그인 페이지 레이아웃
  2. ID, PW 입력 시 로그인 버튼 활성화 기능
  3. 메인 페이지 레이아웃
  4. 댓글 내용 입력 후 Enter press, 혹은 게시 버튼 클릭 시 댓글 추가 기능

이중 4번 제외하곤 스무스하게 했지만 4번은 주변 동기들의 도움이 정말 필요했었다...

4번 항목을 구현하기 위해 짠 html 코드:

JS 코드:

html에 < div id="comment-write">< /div> 를 입력하고
여기에 새로 생기는 코멘트들을 저장해 줌

JS 첫번째 부분은

const submit = document.getElementById('submit')
const comment = document.getElementById('comment')

const commentPost = () => {
    comment.value.length > 0
        ? (submit.disabled = false)
        : (submit.disabled = true);
    submit.style.cursor = 'pointer';
}

comment.addEventListener('keyup', commentPost);

comment 에 한글자라도 입력이 되면 '게시'라고 되어있는 연한 파란색 버튼이 진한 파란색으로 바뀌게 했다.

--아래부터 도움 받은 곳--

const form = document.querySelector(".comment-write");
const commentsContainer = document.querySelector("#comments")

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const input = comment.value;
    comment.value = "";
        const newComment = document.createElement("div");
        
        newComment.innerHTML = `<span class="textbold">Me_me  </span> ${input} <img id="commentHeart" src="../img/heart.png"> `;
        commentsContainer.appendChild(newComment);
 
    
});

코맨트가 입력이 되게 하는법

  1. 페이지를 멈춘다. (클릭이나, 섭밋 될 때 페이지가 새로고침 되지 않게)
    (e.preventDefault(); 이 새로고침 되지 않게 해주는 페이지 이다)

  2. 인풋에 있는 value 를 변수로 저장한다.

  3. 인풋을 다시 빈칸으로 만든다.

  4. createElement로 태그를 만든다. - >변수로 저장

  5. 그 만든 태그에 인풋 value 로 만든 변수를 넣는다

  6. appendChild 이용해서 넣기

0개의 댓글