JavaScript | LOCAL STORAGE CHAT
Тема закрыта by
MIN_MAX
Вот решил немного с помощью ии улучшить чат который скидывали в блог
доступно удаление, редактирование и конечно же поделиться
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Local Storage Chat</title>
</head>
<body>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type your message here...">
<button id="send">Send</button>
<script>
// Get references to the HTML elements
const chatDiv = document.getElementById("chat");
const messageInput = document.getElementById("message");
const sendButton = document.getElementById("send");
// Load existing messages from local storage or create empty array
let messages = JSON.parse(localStorage.getItem("messages")) || [];
// Function to render messages on the page
function renderMessages() {
chatDiv.innerHTML = "";
messages.forEach((message, index) => {
const p = document.createElement("p");
p.textContent = message;
const shareButton = document.createElement("button");
shareButton.textContent = "Share";
shareButton.addEventListener("click", () => {
if (navigator.share) {
navigator.share({
title: "Check out this message!",
text: message,
})
.then(() => console.log("Message shared successfully!"))
.catch((error) => console.log("Error sharing message:", error));
} else {
alert("Sorry, sharing is not supported on this browser/device.");
}
});
const editButton = document.createElement("button");
editButton.textContent = "Edit";
editButton.addEventListener("click", () => {
const newMessage = prompt("Enter new message:", message);
if (newMessage !== null && newMessage.trim() !== "") {
messages[index] = newMessage.trim();
localStorage.setItem("messages", JSON.stringify(messages));
renderMessages();
}
});
const deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", () => {
messages.splice(index, 1);
localStorage.setItem("messages", JSON.stringify(messages));
renderMessages();
});
p.appendChild(shareButton);
p.appendChild(editButton);
p.appendChild(deleteButton);
chatDiv.appendChild(p);
});
}
// Render initial messages on page load
renderMessages();
// Event listener for send button click
sendButton.addEventListener("click", () => {
const message = messageInput.value;
messages.push(message);
localStorage.setItem("messages", JSON.stringify(messages));
renderMessages();
messageInput.value = "";
});
// Event listener for when the page is unloaded (e.g. user closes the tab)
window.addEventListener("unload", () => {
localStorage.setItem("messages", JSON.stringify(messages));
});
</script>
</body>
</html>
доступно удаление, редактирование и конечно же поделиться
DELETED
24 февраля 2023, в 8:53
Delete
Хахахах