Firebase SDK is plug and play
*consider rules with DB codepen is purely an example
initialize
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR DATABASE URL".
projectid: "YOUR_PROJECT_ID",
storageBucket: "YOUR_ STORAGE _BUCKET",
messaging Senderld: "YOUR_MESSAGING_SENDER_ID",
appld: "YOUR_APP_ID"
measurementld: "YOUR_ MEASUREMENT_ID"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
read, write, and display comments
var database = firebase.database();
var commentsContainer = document.getElementById("comments-container");
function displayComments() {
database.ref("comments").on("value", function (snapshot) {
commentsContainer.innerHTML = "";
snapshot.forEach(function (childSnapshot) {
var comment = childSnapshot.val().text;
var timestamp = new Date(childSnapshot.val().timestamp);
var commentElement = document.createElement("div");
commentElement.classList.add("comment");
var commentTextElement = document.createElement("div");
commentTextElement.classList.add("comment-text");
commentTextElement.textContent = comment;
commentElement.appendChild(commentTextElement);
var timestampElement = document.createElement("div");
timestampElement.classList.add("comment-timestamp");
timestampElement.textContent = timestamp.toLocaleString();
commentElement.appendChild(timestampElement);
commentsContainer.appendChild(commentElement);
});
});
}
displayComments();
document
.getElementById("comment-form")
.addEventListener("submit", function (event) {
event.preventDefault();
var commentInput = document.getElementById("comment-input").value;
if (commentInput.trim() !== "") {
var newCommentRef = database.ref("comments").push();
newCommentRef.set({
text: commentInput,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
document.getElementById("comment-input").value = "";
}
});
css to fit your style
body {
font-family: Arial, sans-serif;
background-color: #748b97;
margin: 0;
padding: 0;
}
.container {
max-width: 560px;
margin: 14px auto;
padding: 14px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 7px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
img {
max-width: 100%;
height: auto;
margin-bottom: 14px;
border-radius: 8px;
}
#comments-container {
margin-bottom: 14px;
}
.comment {
background-color: #f9f9f9;
padding: 10px;
border-radius: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.comment-text {
margin-bottom: 5px;
}
.comment-timestamp {
color: #888;
font-size: 0.9em;
}
#comment-form {
display: flex;
}
#comment-input {
flex: 1;
margin-right: 10px;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 16px;
cursor: pointer;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #0056b3;
}
Top comments (0)