Search code examples
javascriptonclickaddeventlistenerappendchildcreateelement

appendChild onclick will only add div once


I'm doing a timetable and to do list website. So, I basically add divs for each timetable block. I've used this tutorial on yt (https://youtu.be/MkESyVB4oUw) for the timetable blocks. (At 24:03) So in HTML there's inputs in a form and he uses the constant "form" for it and uses an addEventListener submit. I've used this and all my timetable blocks work fine. I can add multiple blocks and everything works well.

After that I made a to do / goals section and I decided to take the "form" into my own hands. So I did:

// I tried const and var and the same thing happened
const todoAdd = document.querySelector("#new-todo");   // This is the button
const weekDiv = document.querySelector("#week-divs");

const todoDiv = document.createElement('div');
todoDiv.classList.add("todo-div");

This is what I did for the time blocks and it worked, and then I added:

todoAdd.onclick = function(){
  weekDiv.appendChild(todoDiv);
}

When I do it like this, the div is added once and that's it. If I keep clicking the div just gets replaced again and again.


Solution

  • I figured this out mid-writing it. Because when the addEventListener starts for the form, that's when I did all the appending. So the simple solution to this was simply adding the createElement inside the function.

      todoAdd.onclick = function(){
        const todoDiv = document.createElement('div');
        todoDiv.classList.add("todo-div");
        
        weekDiv.appendChild(todoDiv);
      }
    

    I probably could've realised this sooner if I wasn't so confused about it actually working just once. I thought there was something missing instead of a simple mistake. I'm guessing it only appends once because it is only read once, while in an onclick function or addEventListener it always loops and re-reads it right? That's my thoughts. Hope this helps someone maybe.