In this episode of the Building A Vanilla JavaScript Todo App From Start To Finish we’re starting to add the necessary JavaScript code to our app. We’ll start implement the logic which is needed to add new tasks to the list. Therefore we need to handle the submit event of the form and generate the corresponding list output.
Go to app.js and first of all add and submit event handler function for the submit event type of the form by adding the following line of code:
// Selectors
document.querySelector('form').addEventListener('submit', handleSubmitForm);
Here we’re making use of the document.querySelector method to retrieve an element reference to the form element. Next we’re we’re calling addEventListener to register the handleSubmitForm event handler function to handle the submit event of the form.
The handleSubmitForm function is not existing yet, so we need to implement this function in the next step:
// Event Handlers
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector('input');
if (input.value != '')
addTodo(input.value);
input.value = '';
}
Inside this function we’re first making sure that the default form submit behaviour of the browser is not taking place by calling e.preventDefault(). Next we’re retrieving an reference to the input element by using the querySelector method once again. We’re storing that element reference in input, so that we’re able to access the input value by using input.value.
If the input value if not empty the addTodo helper function is called and the current input value is passed into that function as a parameter.
Finally the input value is reset to an empty string.
Let’s implement the addTodo helper function as well:
// Helpers
function addTodo(todo) {
let ul = document.querySelector('ul');
let li = document.createElement('li');
li.innerHTML = `
<span class="todo-item">${todo}</span>
<button name="checkButton"><i class="fas fa-check-square"></i></button>
<button name="deleteButton" ><i class="fas fa-trash"></i></button>
`;
li.classList.add('todo-list-item');
ul.appendChild(li);
}
First of all a reference to the ul element is retrieved. Next a new li element is created by using the document.createElement method. This is new element is stored in the variable li. This is the list element which is containing the output which is done for every todo element. Therefore we’re inserting the inner HTML code of the li element by assigning the code string to property innerHTML of the li element.
The output consists of the todo text, a check button and a delete button.
Finally the new li element is added as a child to the ul element, so that it becomes visible in the browser.
What’s Next
In the next episode we’re going to complete the JavaScript todo application by adding the check and delete functionality.