Design a Nested Chat Comments using HTML CSS and JavaScript (original) (raw)
Last Updated : 26 Jul, 2024
In this article, we will learn how to create Nested Comments using JavaScript. We must have seen it on social media like Facebook, Instagram, Youtube, Twitter, etc. We have seen the use of the nested comment in the comment section of these social sites.
**Approach:
- Create a folder **nested-comments on your local machine and go to that folder.
- Create 3 files inside that folder **index.html, **style.css, **script.js
**Example: In this example, we will create the Nested Comments using Javascript.
HTML `
Nested Comments<script src="script.js"></script>
CSS
.card { height: auto; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); border-radius: 10px; padding: 10px; background-color: rgb(222, 222, 222); margin-top: 10px; } .text { display: block; font-size: 20px; font-weight: bold; } .reply { color: rgb(84, 84, 233); cursor: pointer; margin-top: 5px; } .comment-details { margin-left: 4rem; display: flex; align-items: center; margin-top: 10px; } .input { height: 30px; border-radius: 10px; } .btn { color: white; margin-left: 5px; background-color: rgb(135, 135, 235); border: 0px; border-radius: 10px; height: 30px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); cursor: pointer; } .all-comment:not(:first-child) { margin-left: 4rem; }
` JavaScript ``
let commentContainer = document.getElementById("comment-container");
function createInputBox() { let div = document.createElement("div");
div.setAttribute("class", "comment-details");
div.innerHTML += `<input type="text"
placeholder="add text here"
class="input" />
<button class="btn submit">
Submit
</button>`;
return div;
}
function addReply(text) { let div = document.createElement("div");
div.setAttribute("class", "all-comment");
div.innerHTML += `<div class="card">
<span class="text">
${text}
</span>
<span id="reply" class="reply">
Add Reply
</span></div>`;
return div;
}
commentContainer.addEventListener("click", function (e) { let replyClicked = e.target.classList.contains("reply"); let submitClicked = e.target.classList.contains("submit"); let closestCard = e.target.closest(".all-comment");
if (replyClicked) {
closestCard.appendChild(createInputBox());
}
if (submitClicked) {
const commentDetails =
e.target.closest(".comment-details");
if (commentDetails.children[0].value) {
closestCard.appendChild(
addReply(commentDetails.children[0].value));
commentDetails.remove();
}
}
});
``
**Output: