diff --git a/index.html b/index.html index 6f14ae14a..1044012ff 100644 --- a/index.html +++ b/index.html @@ -1,4 +1,4 @@ - +d Проект "Комменты" @@ -65,7 +65,123 @@ + const nameInput = document.querySelector('.add-form-name'); + const commentInput = document.querySelector('.add-form-text'); + const addButton = document.querySelector('.add-form-button'); + const commentsEl = document.querySelector('.comments'); + + const formatDate = () => { + const date = new Date(); + return date.toLocaleString('ru-RU', { + day: '2-digit', + month: '2-digit', + year: '2-digit', + hour: '2-digit', + minute: '2-digit' + }).replace(',', ''); + }; + + const sanitizeHtml = (text) => { + return text.replaceAll('<', '<').replaceAll('>', '>') + }; + + let comments = [ + { + userName: "Глеб Фокин", + date: "12.02.22 12:18", + commentText: "Это будет первый комментарий на этой странице", + likes: 3, + isLiked: false + }, + { + userName: "Варвара Н.", + date: "13.02.22 19:22", + commentText: "Мне нравится как оформлена эта страница! ❤", + likes: 75, + isLiked: true + } + ]; + + const renderComments = () => { + commentsEl.innerHTML = comments.map((comment, index) => { + return ` +
  • +
    +
    ${sanitizeHtml(comment.userName)}
    +
    ${comment.date}
    +
    +
    +
    ${sanitizeHtml(comment.commentText)}
    +
    + +
  • + `; + }).join(''); + }; + + renderComments(); + + addButton.addEventListener('click', () => { + const userName = sanitizeHtml(nameInput.value.trim()); + const commentText = sanitizeHtml(commentInput.value.trim()); + + if (!userName || !commentText) { + alert('Необходимо заполнить все поля'); + return; + } + + const newComment = { + userName: userName, + date: formatDate(), + commentText: commentText, + likes: 0, + isLiked: false + }; + + comments.push(newComment); + renderComments(); + + nameInput.value = ''; + commentInput.value = ''; + }); + + commentsEl.addEventListener('click', (event) => { + if (event.target.classList.contains('like-button')) { + event.stopPropagation(); + const commentElement = event.target.closest('.comment') + const index = commentElement.dataset.index; + const comment = comments[index]; + + if (event.target.classList.contains('-active-like')) { + comment.likes--; + comment.isLiked = false; + } else { + comment.likes++; + comment.isLiked = true; + } + + renderComments(); + return; + } + + const commentElement = event.target.closest('.comment'); + if (commentElement) { + const index = commentElement.dataset.index; + const comment = comments[index]; + + nameInput.value = comment.userName; + commentInput.value = `> ${comment.commentText}\n\n`; + + commentInput.focus(); + } + }); + + console.log("It works!"); +