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
클래스를 생성해서 버튼이 활성화 되지 못하도록 했다.
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);
}
onAdd()
함수는 input에 들어오는 입력값을 createItem
에 전달 후 초기화 시키는 역할을 담당하도록 했다.
createItem()
함수는 입력 값을 받으면 그 입력값을 반영한 li
요소를 생성해내도록 구현했다.
innerHTML
및 setAttribute
를 사용해 기존 li
요소들과 양식을 맞추도록 했고, 만들어낸 요소를 HTML에 연결시켜야 하기에, 부모 요소가 될 replies
라는 클래스를 가진 ul
에 appendChild
를 활용해서 묶어줬다.
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()
함수를 실행하도록 조건문을 걸어 값이 빈 경우 댓글 추가가 되는 것을 제한하였다.