Javascript addEventlistener "click" not working

I am working on creating a To-Do list as an extension of the new Chrome tab.

My html file:      

<head>
</head>

<body>
    <h2 id="toc-final">To Do List</h2>
    <ul id="todoItems"></ul>
    <input type="text" id="todo" name="todo" placeholder="What do you need to do?" style="width: 200px;">
    <button id="newitem" value="Add Todo Item">Add</button>

    <script type="text/javascript" src="indexdb.js"></script>
</body>
</html>

Previously, the button element was an input type with onClick (), but Chrome does not allow this. So I had to create a javascript function that will fire when it is closed. In my indexdb.js:

var woosToDo = {};
    window.indexedDB = window.indexedDB || window.webkitIndexedDB ||
                    window.mozIndexedDB;

    woosToDo.indexedDB = {};
    woosToDo.indexedDB.db = null;

    window.addEventListener("DOMContentLoaded", init, false);

    window.addEventListener('DOMContentLoaded', function () {
      document.getElementById("newitem").addEventListener("click", addTodo(), false);
    });

...
...

    function addTodo() {
      var todo = document.getElementById("todo");
      woosToDo.indexedDB.addTodo(todo.value);
      todo.value = "";
    }

Why does nothing happen when I press the w / id = "newitem" button?

+4
source share
2 answers

When attaching a function, you execute it first and attach the return value to the event undefined. Remove the brackets:

.addEventListener("click", addTodo, false);

Edit: clarification.

addTodo() , . , , .

return undefined, , :

.addEventListener("click", undefined, false);
+5

DOMContentLoaded .

:

window.addEventListener("DOMContentLoaded", init, false);

    window.addEventListener('DOMContentLoaded', function () {
      document.getElementById("newitem").addEventListener("click", addTodo(), false);
    });

:

window.addEventListener('DOMContentLoaded', function () {
  init();
  document.getElementById("newitem").addEventListener("click", addTodo, false);
});
-1

Source: https://habr.com/ru/post/1617342/


All Articles