Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function general() {
- let topic = document.querySelector('#idPost');
- let time = document.querySelector('#idTime');
- let subscribers = document.querySelector('#some')
- let body = document.querySelector('body');
- body.addEventListener('click', (e) => service(e))
- function service(e) {
- e.preventDefault();
- e.stopImmediatePropagation();
- if (e.target.textContent === "Home") {
- window.location.href = 'index.html'
- } else if (e.target.textContent === "Post") {
- e.preventDefault()
- let comment = document.querySelector('#comment');
- let username = document.querySelector('#username')
- if (comment.value.trim() === "" || username.value.trim() === "") {
- alert('Empty fields are not allowed. Please try again!')
- } else {
- addCommentToServer({
- comment: comment.value,
- username: username.value,
- topic: sessionStorage.getItem('target')
- })
- comment.value = ""
- username.value = ""
- addAllCommentsToHTML()
- }
- }
- }
- async function addAllCommentsToHTML() {
- let div = document.querySelector('#allComments')
- div.innerHTML = ""
- let response = await fetch('http://localhost:3030/jsonstore/collections/myboard/comments')
- let data = await response.json();
- Object.values(data).forEach(c => {
- if (sessionStorage.getItem('target') === c.topic) {
- div.insertAdjacentHTML('beforeend', returnHtmlStringComment(c.comment, c.username))
- }
- })
- }
- async function addCommentToServer(obj) {
- let response = await fetch('http://localhost:3030/jsonstore/collections/myboard/comments', {
- method: 'post',
- headers: {'Content-type': 'application/json'},
- body: JSON.stringify(obj)
- })
- let data = await response.json();
- }
- function returnHtmlStringComment(comment, username) {
- let date = new Date();
- let htmlString = ` <div class="comment">
- <header class="header">
- <p><span>${username}</span> posted on <time>${date.toLocaleString()}</time></p>
- </header>
- <div class="comment-main">
- <div class="userdetails">
- <img src="./static/profile.png" alt="avatar">
- </div>
- <div class="post-content">
- <p>${comment}</p>
- </div>
- </div>
- <div class="footer">
- <p><span>0</span> likes</p>
- </div>
- </div>`;
- return htmlString;
- }
- topic.textContent = sessionStorage.getItem('target')
- time.textContent = sessionStorage.getItem('time')
- subscribers.textContent = sessionStorage.getItem('subscribers')
- addAllCommentsToHTML()
- }
- general()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement