Skip to content

Instantly share code, notes, and snippets.

@kraigh
Last active November 6, 2018 22:01
Show Gist options
  • Save kraigh/4baf1a4dcf9d795bca33d350fc77fdde to your computer and use it in GitHub Desktop.
Save kraigh/4baf1a4dcf9d795bca33d350fc77fdde to your computer and use it in GitHub Desktop.
// This would go inside the fuction that gets called after your list (GET) AJAX completes and you have an array of ToDos
for (let index = 0; index < todos.length; index++) {
// Create todo container
var todo = document.createElement("article");
todo.setAttribute("id", todos[index].id);
todo.setAttribute("class", "todo");
if (todos[index].completed) {
todo.classList += " completed";
}
// ... add a completed button ...
// Create todo text
var todoText = document.createElement("p");
todoText.innerHTML = todos[index].text;
todo.appendChild(todoText);
// ... add a delete button ...
// Add your todo to your list of todos
document.getElementById("todos").appendChild(todo);
// Alternate approach
// var todo = todos[index];
// if (todo.completed) {
// var classes = 'todo checked';
// } else {
// var classes = 'todo';
// }
// var newTodo = '<article class="'+classes+'" id="' + todo.id + '"><button type="button" class="check"></button><p>' + todo.text + '</p><button type="button" class="delete">-</button></article >';
// document.getElementById("todos").innerHTML += newTodo;
// "completeButton" here is an element created above. Could also use "document.getElementById(".your-complete-button").addEventListener...
completeButton.addEventListener("click", completeTodo);
}
// Function to call when user clicked on a "complete" button to check off a ToDo
var completeTodo = function(event) {
var todoId = event.srcElement.parentNode.id;
// the URL you need to submit the PUT to, with the ID added
var url = "https://api.kraigh.net/todos/"+todoId;
// the JSON string object you need to send in your PUT request
var data = JSON.stringify({
"completed": true
});
// ... do your PUT request
// ... if PUT request is successful, add a class to your ToDo element, like:
event.srcElement.parentNode.classList += " completed"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment