Skip to content

Instantly share code, notes, and snippets.

@krawaller
Created April 16, 2018 08:43
Show Gist options
  • Save krawaller/c2987d64797897d09448a27de8a676ad to your computer and use it in GitHub Desktop.
Save krawaller/c2987d64797897d09448a27de8a676ad to your computer and use it in GitHub Desktop.
Todo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.done {
background-color: #DDD;
text-decoration: line-through;
}
</style>
</head>
<body>
<form>
<input id="field">
<input type="submit" value="Add">
</form>
<hr/>
<ul id="list"></ul>
<button id="clear">Clear all done</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function render(items) {
let html = '';
for(let i in items){ // not using for-of since i need the key too
html += `
<li data-pos="${i}" class="${items[i].done ? 'done' : ''}">
<span class="toggle">${items[i].text}</span>
<button class="delete">X</button>
</li>
`;
}
$("#list").html(html);
}
let myItems = [{text:"Carpe diem"}];
$("form").submit(function(e){
e.preventDefault(); // stop page from reloading
let newItem = $("#field").val();
myItems.push({text:newItem});
render(myItems);
$("#field").val(""); // empty field
});
$("#list").on("click", ".delete", function(){
let delIndex = parseInt($(this).closest("li").attr("data-pos"));
myItems.splice(delIndex, 1); // removes 1 item starting from delIndex
render(myItems);
});
$("#list").on("click", ".toggle", function(){
let toggleIndex = parseInt($(this).closest("li").attr("data-pos"));
myItems[toggleIndex].done = !myItems[toggleIndex].done;
render(myItems);
});
$("#clear").click(function(){
let remaining = [];
for(let item of myItems){
if (!item.done){
remaining.push(item);
}
}
myItems = remaining;
render(myItems);
});
render(myItems);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment