I have just started learning javascript. I am creating a ToDo app. Whenever I click on Add Task button the myFunction which I created is not working as it suppose to. Whenever the button is clicked it takes seconds to respond plus the output on console is being multiplied. Thanks in advance. Much Appreciated.
function myFunction() {
// code to be executed when the button is clicked
const taskInput = document.getElementById("taskInput");
const taskList = document.getElementById("taskList");
//const task = taskInput.value.trim();
const myButton = document.getElementById("mButton");
//document.getElementById("taskList").innerHTML = userInput;
myButton.addEventListener("click", function() {
const li = document.createElement("li");
li.createElement = '${taskInput.value} <button class="delete" onclick="deleteTask">Delete</button>';
console.log("I m clicked");
});
}
<script src="script.js"></script>
<div class="container">
<h3>To-Do List</h3>
<input type="text" id="taskInput" placeholder="Enter a task" />
<button id="mButton" onclick="myFunction()">Add Task</button>
<ul id="taskList"></ul>
</div>
The <button>
itself has an onclick
attribute which means myFunction()
gets called every time it is clicked. In myFunction
, you are adding another event handler via myButton.addEventListener
, but the original one is still there, so next time you click the button both myFunction()
and the new handler function get called. The myFunction
call then adds yet another event handler, and so on. You keep adding new event handlers and are never removing any of them.