<div class="container">
      <h1>Firebase TodoList reverse</h1>

      <input type="text" id="memo" placeholder="請輸入待辦事項" />
      <button id="btn">送出</button>
      <ul id="list"></ul>
    </div>
.container {
  margin: 0 auto;
  width: 800px;
}

#memo {
  width: 300px;
  padding: 12px;
  font-size: 16px;
  border-radius: 6px;
  border: 1px solid #666;
}

#btn {
  padding: 12px 20px;
  font-size: 14px;
  background-color: green;
  border: none;
  color: #fff;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.5s ease-in-out;
  &:hover {
    background: darken($color: green, $amount: 10%);
  }
}

#list > li {
  line-height: 1.8;
  color: #333;
  font-size: 18px;
  &:hover {
    font-weight: bold;
    color: orangered;
    cursor: pointer;
    transition: all 0.6s;
  }
}
View Compiled
const firebaseConfig = {
  apiKey: "AIzaSyDhtziAvRJxhkVpSR8Lfb6JqZ1GE-jBfuY",
  authDomain: "nodejsproject-d099d.firebaseapp.com",
  projectId: "nodejsproject-d099d",
  storageBucket: "nodejsproject-d099d.appspot.com",
  messagingSenderId: "620886577949",
  appId: "1:620886577949:web:bb7819e6cb71ffb05307f4",
  measurementId: "G-CKJW9DEX9H",
};

firebase.initializeApp(firebaseConfig);

// DOM

let memo = document.querySelector("#memo");
const btn = document.querySelector("#btn");
const list = document.querySelector("#list");

// data
const todo = firebase.database().ref("todo");

// click
btn.addEventListener("click", function (e) {
  console.log(memo.value); //確認取得 input 的值
  //* 把 input 的值新增到 Firebase
  todo.push({ content: memo.value });
});

// on

todo.on("value", function (snapshot) {
  let str = "";
  let data = [];
  snapshot.forEach((item) => {
    data.push(item.val());
  });

  data.reverse(); //* 反轉陣列資料

  for (let item in data) {
    str += `<li>${data[item].content}</li>`; //* 累加列表
  }

  list.innerHTML = str;
  memo.value = ""; //* 按下送出後,清空 input 的值
});


External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js
  2. https://www.gstatic.com/firebasejs/8.9.1/firebase-database.js