HTML
For the html you'll simply need an input
element and a button that'll be used to add the task, below them is a div element with a list that's where the tasks will be at. You can also add a placeholder to the input if you want or just stylize it. Each of these elements will have an id that we'll use to attatch the javascript. We can also use a checkbox but the javascript for it is a little bit more complex so i'll just go with the simple way.
<html>
<body>
<!--we put them in a div so they can be aligned-->
<div>
<input placeholder="Add a task!" id="enterTask">
<button id="AddBtn">Create</button>
</div>
<div>
<ul id="taskList">
</ul>
</div>
</body>
</html>
Creating tasks
First we need to get the input, button, and unordered list element stored in a variable. Next we give the button an event listener since it'll be the button that'll add the task. We'll set it to click and give it a function. Inside the function we make a variable called task with a li
element in it. its HTML will be the same as the inputs value meaning whatever the user put in the input element will be the list items text. Finally we add it's parent by using appendChild
on the list area and setting it to the task variable.
When you run this it should add tasks that you type in the input!
var input = document.getElementById('enterTask');
var button = document.getElementById('addBtn');
var listArea = document.getElementById('taskList');
button.addEventListener('click', function() {
//adding the tasks
var task = document.createElement('li');
task.innerHTML = input.value;
listArea.appendChild(task);
});
Deleting tasks
To delete them you have to give the task/list item an event listener INSIDE the buttons event listener. This is because the variables are local, meaning they only work inside the function in the event listener. We gave the task a click event and a function that uses removeChild
to delete the task area's child. Under the event listener we'll put an if statement, with it's condition being that if the length of the input is 0 the task will automatically delete before its seen. This is so nobody can make empty tasks.
button.addEventListener('click', function() {
//adding the tasks
var task = document.createElement('li');
task.innerHTML = input.value;
listArea.appendChild(task);
//deleting the tasks
task.addEventListener('click', function() {
listArea.removeChild(task);
})
if (listLength.length === 0) {
listArea.removeChild(task);
}});
How to stylize
A bulleted point isn't a good look on a list item, so we can take it off by setting the ul's list type to none. You can also give it an outline with a border and space each list item by adding gaps. The rest is up to you! After all you can make a to-do list in any way you want. Try to get creative with the looks, like how i gave mine an animation whenever a new task was made!
Top comments (0)