1

I am using addEventListener to bind an event to a node. The addEventListener adds addItem function to node. But when I press enter the function is not running.

Here is the JavaScript:

document.getElementById('add-item').addEventListener('keypress', function (e) {
    if (e.keyCode == 13) {
            addItem();
    }
}, false);

function addItem() {
    var list = document.querySelector('ul.todo-list');
    var newItem = document.getElementById('new-item-text').value;
    var newListItem = document.createElement('li');
    newListItem.className = 'todo-item';
    newListItem.innerHTML = newItem + '<span class="remove"></span>';
    list.insertBefore(newListItem, document.querySelector('.todo-new'));

    //1. Empty the Input field once the item 
    document.getElementsByTagName('input')[0].value = '';
}

Here is the HTML:

<li class='todo-new'>
    <input id='new-item-text' type='text'/>
    <a id='add-item' href='#'>+</a>
</li>

On other hand the function runs with click

document.getElementById('add-item').addEventListener('click', addItem, false);

I want to do this with JavaScript only not using jQuery library.

Edited: I want to attach the event to input field.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

1 Answers1

3

I'm willing to place a bet that the add-item element isn't in focus when you press enter. Instead, try changing the trigger to be the input field.

document.getElementById('new-item-text').addEventListener('keypress', function (e) {
    if (e.keyCode == 13) {
            addItem();
    }
}, false);
Lewis
  • 3,479
  • 25
  • 40