프론트엔드 개발자가 될거야./js

[instagram 클론코딩] input 창에 엔터치거나 "게시"누르면 댓글 추가 구현하기

정니정은니 2022. 6. 29. 08:47

 

엔터치거나 "게시"누르면 댓글 추가

짠~~ 나만의 인스타그램을 만들었다.

레이아웃에 대해서도 할 말이 많지만 

일단 이 게시물에는 JS로 구현한 사항에 대한 것만 작성해보려고 한다.

 

구현해야 할 사항은

댓글 input 창에 엔터치거나 "게시" 누르면 댓글 추가되도록 createElement로 요소 생성해서, input에 입력한 값이 추가 되어야합니다.

나의 코드

const input = document.querySelector('.input__comment');
const submit = document.querySelector('.input__submit');
const parentComment = document.querySelector('.contents__comments');

function isEnter(e) {
  let div = document.createElement('div')
  div.className = 'yourComment'
  let span = document.createElement('span')
  span.className = 'comment1'
  span.innerHTML = `<span class="bold">freindID</span>&nbsp;&nbsp;${input.value}`
  parentComment.appendChild(div)
  div.appendChild(span)
  input.value = ''; 
}

input.addEventListener('keydown', (e) => {
  console.log(e)
  if(e.key === 'Enter') {
    isEnter()
  }
})

submit.addEventListener('click', isEnter)

👩🏻‍💻코드분석👩🏻‍💻

 

먼저, 이벤트를 적용해야하는 input, submit을 가져왔고

댓글이 .contents__comments의 맨 하위에 넣어져야하므로 .contents__comments도 가져왔다.

const input = document.querySelector('.input__comment');
const submit = document.querySelector('.input__submit');
const parentComment = document.querySelector('.contents__comments');

그리고

input창에 엔터치거나

'게시'를 누르면 

댓글기능이 추가되어야 하기때문에

아래처럼 코드를 추가해줬다.

input.addEventListener('keydown', (e) => {
  console.log(e)
  if(e.key === 'Enter') {
    isEnter()
  }
})

submit.addEventListener('click', isEnter)

여기서 짚고 넘어가야 할 것은

자바스크립트 키보드 이벤트

  1. keydown : 키보드의 키를 누르면 keydown이벤트 시작 (모든 키에서 작동)
  2. keypress : 문자, 숫자를 표시하는 키를 누를 때 발생. 즉 스페이스 바, 화살표 키 등을 누르면 이벤트 발생 X
  3. keyup : 방금 누른 키를 놓으면 keyup 이벤트 시작 (모든 키에서 작동)

이 세 이벤트는 keydowm -> keypress -> keyup 순서로 이벤트가 실행된다.

하지만, 실제 글자가 입력되는 상황에서의 동작 순서는 다음과 같다고 한다.

① 키보드 'G'를 누른다.
② keydown 이벤트가 발생한다. (input text 창에는 'G'가 입력이 반영되지 않은 상태.)
③ 'G'가 입력된다. (input text 창에 입력한 'G'가 반영된 상태/)
④ keypress 이벤트가 발생한다.
⑤ 'G' 키에서 손을 뗀다.
⑥ keyup 이벤트가 발생한다.
이 블로그를 참고했다🙂

e.key === 'Enter'

이것은 내 키보드가 지금 엔터를 했는지 알 수 있는 코드다.

input.addEventListener('keypress', (e) => {
  console.log(e)
  if(e.code === 'Enter') {
    isEnter()
  }
})

input에 keypress를 해주고 console.log(e)로 어떤 이벤트가 발생했는지 보면

이렇게 콘솔에 발생한 이벤트를 볼 수 있다.

여기서 

code: "Enter"
key: "Enter"
keyCode: 13

이 세개에서 엔터를 눌렀음을 알 수 있다.

즉, 

(e.code === 'Enter')
(e.key === 'Enter')
(e.keyCode === 13)

이 세개가 같은 거라고 보면 된다.


그리고 input과 submit에 적용해야하는 isEnter()함수를 짰다.

function isEnter(e) {
  let div = document.createElement('div')
  div.className = 'yourComment'
  let span = document.createElement('span')
  span.className = 'comment1'
  span.innerHTML = `<span class="bold">freindID</span>&nbsp;&nbsp;${input.value}`
  parentComment.appendChild(div)
  div.appendChild(span)
  input.value = ''; 
}

createElement로 div태그 만들어주고

그 div태그에 yourComment클래스를 넣어줬다.

(yourComment클래스를 넣어줘야 스타일 적용이 되기 때문에)

아래도 똑같이

createElement로 span태그 만들어주고

그 span태그에 comment1클래스를 넣어줬다.

그리고 

span.innerHTML = `<span class="bold">freindID</span>&nbsp;&nbsp;${input.value}`이거는

그 span의 text부분에 넣어준건데

<span class="bold">freindID</span>로 인스타아이디를 넣어줬고

&nbsp;&nbsp;로 띄어쓰기 해주고

${input.value}로 input의 값을 넣어줬다.

 

div와 span에 필요한 것을 다 넣어줬기 때문에

appendChild로 태그를 위치시켜줬다.

 

그리고 다 했을 때

input.value = '';  해서

input 박스가 비어있게 해주었다.


되게 간단해 보이는데 왜 이렇게 복잡했을까..!!

그래도 내가 만든 코드로 이벤트가 잘 동작하여 구현되는 걸 보니

신기하고 재밌다.

더 잘하고 싶다👩🏻‍💻👩🏻‍💻👩🏻‍💻👩🏻‍💻👩🏻‍💻

 

참고한 블로그

https://hianna.tistory.com/469

 

[Javascript] class 추가/변경/삭제/읽기 (className, classList)

class 이름 읽기 class 추가/수정 class 삭제 class toggle 특정 클래스 이름이 class 속성에 포함되는지 확인하기 1. class 이름 읽기 예제 1. className function handleOnClick() { alert(document.getElementB..

hianna.tistory.com