Skip to content

Instantly share code, notes, and snippets.

@afropolymath
Created October 4, 2016 00:46
Show Gist options
  • Save afropolymath/aa4363db78c3dce783b3f1bd4489cd89 to your computer and use it in GitHub Desktop.
Save afropolymath/aa4363db78c3dce783b3f1bd4489cd89 to your computer and use it in GitHub Desktop.
Create a Firebase Todo
<html>
<head>
<title>Firebase Todo</title>
</head>
<body>
<input type="text" id="new-todo" placeholder="Enter a new todo item" />
<button id="create-todo">Create Todo</button>
<ul id="todo-list">
<li></li>
</ul>
<script src="https://www.gstatic.com/firebasejs/3.4.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyALnTxXLYH7gAyVZcXOyemVq6XV4XH7xDg",
authDomain: "createtodolist.firebaseapp.com",
databaseURL: "https://createtodolist.firebaseio.com",
storageBucket: "createtodolist.appspot.com",
messagingSenderId: "579045395654"
};
firebase.initializeApp(config);
//-- What happens when we click a button
//-- Take what is in the textbox and store it in a variable
//-- Write variable into database
var createTodoButton = document.getElementById('create-todo')
var newTodo = document.getElementById('new-todo')
var todoList = document.getElementById('todo-list')
var database = firebase.database() // Connected to our database
var todosRef = database.ref('todos')
// Create an event listener that triggers everytime there's a change on the todos node
todosRef.on('value', function(snap) {
var data = snap.val()
var listItems = ""
for(i in data) {
listItems += '<li>' + data[i] + ' <button>Delete</button></li>'
}
todoList.innerHTML = listItems
})
var addTodoItem = function(todoItem) {
// .push() creates a new reference nested under the node
// With push i dont have to create a new node. It adds to the specific node.
todosRef.push(todoItem, function() {
newTodo.value = ""
})
}
createTodoButton.addEventListener('click', function() {
var todoItem = newTodo.value
addTodoItem(todoItem)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment