Search code examples
javascriptevent-listenerappendchild

Appended item is instantly removed


I am trying to understand the basics of eventListeners, i have created a simple form where i just want to add a value of an input to a UL, however when i append the value, i am able to see it in the list for a brief second and then it is instantly removed, i cannot figure out why, could anyone help?.

const submitButton = document.querySelector('#add-task-btn');
const clearButton = document.querySelector('#remove-task-btn');
const item = document.querySelector('#task');
const taskList = document.querySelector('.collection');

allEventListeners();

function allEventListeners(){

    submitButton.addEventListener('click', function(){

        if (item.value === ''){
            alert('Please add a task')
        };

        const li = document.createElement('li');
        li.appendChild(document.createTextNode(item.value));

        taskList.appendChild(li);

        item.value = "";

    })
}

Solution

  • You just need to provide an event parameter for your handler function and then call preventDefault()

    submitButton.addEventListener('click', function(ev){
      ev.preventDefault(); // prevent the page submit
    
      //...
    
    });