For this post, I will try to explain dynamically created buttons as I understand the concept. The implementation of this code is done via an independently created library that is similar to jQuery but was created for the purpose of learning and understanding what a library is and how it can be used in our code.
When you want to create a component that is not part of your original HTML, you manipulate the DOM in order to get that component to display. This component can be created as a result to the user doing a certain action, completing a form, and/or clicking on a certain button. In our example, we will create a button as a result of clicking on another button with the id #add.
Why didn't this work? Our code is written correctly but we did not see a new message in the console. This is a rather hard concept to grasp and it has to do with dynamically changing our DOM and with the concept of Bubbling and Capturing.
The way I think about it is that the new button was not in the initial code thus our function did not have a point of reference to attach our listener (the click event) to our new button. Rephrased: our testMyNewButton function could not be tied to #myNewButton because that button was not part of the initial html that loaded.
So instead, lets add the function to something that was already there. We can association the function to clicking on the document, on the body, or any other component that was in the origin HTML. For this example, we will associate the function to clicking on the div with the .container class as this is the div we appended the new button to.
Seems to work well! But what if I click to the right of our new button?
Our console logs another message here too. This is consistent with our code. Remember, we associated the function to the entire .container div thus we expect the function to run upon clicking anywhere inside of .container :
To fine tune and solely associate the click event to our new button, lets add some conditions to our function in order to check on the id of the element the user clicked on. To start, lets create a variable that will store the id of the element we will click on. To do this, we will use our initial "submittedOrClickedEvent" parameter and grab the target. The target will be the inner most element where our click event originated from. If that element has an id, we will want to store it: