Westagram Login 페이지에 이어서 Main 페이지를 작업했다.
Main 페이지에서 구현한 주요 기능은,
1. 댓글 달기 기능 구현
2. 댓글 삭제 기능 구현
이다.
댓글 input 창에 댓글을 입력하면, <게시> 버튼이 활성화 되고 클릭하거나 enter 를 치면 댓글이 달리는 기능을 구현했다.
버튼이 활성화 되는 코드는 지난번에 로그인 버튼 활성화하는 코드와 동일해서 패스하도록 하겠다.
댓글을 달려면 아이디, 댓글, 삭제 버튼이 추가 되어야 한다.
차근차근 생각해보자.
아이디가 추가되려면,
1. span tag를 추가하고
2. 안에 아이디를 text로 추가하고
3. 아이디에 CSS를 입히기 위해서 class를 추가하고
4. 이렇게 만들어진 span 을 li에 넣어주고
5. li>span 을 큰 태그인 ul에 넣어준다. => ul>li>span
JS는 이러한 코드가 된다.
댓글 내용과 댓글 삭제 버튼도 같은 로직으로 만들어준다.
삭제 버튼은 안에 함수를 추가해준다.
const input = document.querySelector(".article_typingReply"); // input을 가져옴
const replyBtn = document.querySelector(".article_replyPush"); // 게시 버튼
// 게시버튼 활성화시키기
function checkReply () {
const inputValue = input.value;
if (inputValue.length > 0) {
replyBtn.disabled = false;
replyBtn.style.cursor = "pointer";
replyBtn.style.opacity = 1;
} else {
replyBtn.disabled = true;
replyBtn.style.cursor = "default";
replyBtn.style.opacity = 0.3;
}
}
// 댓글달기
function addReply (value) {
const comment = document.querySelector(".article_reply"); // ul 태그의 class명
const newComment = document.createElement('li'); // li 태그
const newId = document.createElement('span'); // span 태그 만들고
newId.innerText = "boooni.k"; // innerText로 아이디 추가
newId.classList.add("replyId"); // class 추가해서 css 기능
newComment.appendChild(newId); // 만들어진 댓글을 li의 자식으로 넣어줌
comment.appendChild(newComment); // li를 ul에 넣어줌
value = input.value; // 댓글 내용을 받음
const newReply = document.createElement('span'); // span 태그 만들고
newReply.innerText = value; // innerText로 내용 추가
newComment.appendChild(newReply); //
comment.appendChild(newComment);
const newDelete = document.createElement('span');
newDelete.innerText = "X";
newDelete.classList.add("replyDelete");
newComment.appendChild(newDelete);
comment.appendChild(newComment);
const deleteBtn = () => {
newComment.remove();
}
newDelete.addEventListener('click', deleteBtn);
}
function replyClick () {
addReply();
input.value = "";
}
function enterKey (e) {
if (e.code === "Enter" || e.code === "NumpadEnter") {
e.preventDefault();
addReply();
input.value = "";
}
}
replyBtn.addEventListener('click', replyClick);
input.addEventListener('keyup', checkReply);
input.addEventListener('keydown', enterKey);