-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
79 lines (79 loc) · 1.87 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!doctype html>
<html>
<head>
<style>
span + a {
display: inline-block;
margin-left: 1em;
cursor: pointer;
}
</style>
</head>
<body>
<form>
<label for='todo'>Todo:</label>
<input type='text' id='todo'>
</form>
<ul class='todos'></ul>
<script>
var apiUrl = 'https://stopgap.store/48277/todos'
var form = document.querySelector('form')
var input = document.getElementById('todo')
var todos = document.querySelector('.todos')
form.addEventListener("submit", create)
function create(event){
event.preventDefault()
fetch(apiUrl,{
method: 'POST',
body: JSON.stringify({
text: input.value
})
}).then(function(response){
response.json().then(li)
})
}
function update(event){
var id = event.target.getAttribute("data-id")
fetch(apiUrl + "/" + id + ".json", {
method: 'PATCH',
body: JSON.stringify({
text: event.target.innerText
})
}).then(function(response){
response.json().then(function(todo){
console.log(todo)
})
})
}
function li(todo){
var l = document.createElement("li")
var span = document.createElement("span")
span.setAttribute("contenteditable", true)
span.setAttribute("data-id", todo.id)
span.innerHTML = todo.text
span.addEventListener("blur", update)
l.appendChild(span)
var a = document.createElement("a")
a.innerHTML = '×'
a.addEventListener("click", remove)
a.setAttribute("data-id", todo.id)
l.appendChild(a)
todos.appendChild(l)
}
function remove(event){
event.preventDefault()
var id = event.target.getAttribute("data-id")
fetch(apiUrl + "/" + id,{
method: 'DELETE'
}).then(function(){
todos.removeChild(event.target.parentNode)
})
}
fetch(apiUrl + ".json").then(function(response){
response.json().then(function(todos){
todos.forEach(li)
})
})
</script>
</body>
</html>