Table of contents
Creating some markup
Let’s create some HTML to get started from, I am going to take the list scenario into account here, and create a simple <ul> with some links inside:
Creating an onclick function
To create an onclick function is simple, we just target our element, and setup a click handler:
It’s good practice to setup functions separately and then call them like so, especially when dealing with loops:
Attaching an onclick function
Taking our knowledge from above, we can loop through our HTML and attach the event handler to each <li> tag.
First I’m going to setup querySelector, a native DOM selector, in a jQuery-style way using the dollar symbol:
This allows us to do this to target what we need:
Using querySelector, let’s target our #links ID, and then find the list elements inside. We could use $(‘#links li’) but this would require querySelectorAll instead. I’ve then looped through the array of links, attaching the above ‘myFunction’ to each element.
That’s great, but let’s add a real function called dynamicEvent:
So far we’ve attached an onclick event handler to each static item on the page, which is easy. When we click on them now, they will run the dynamicEvent function and the text will change to ‘Dynamic event success.’.
Dynamically creating elements
Attaching the event dynamically
This is a lot simpler than you think, in our function that will create our new element, we need to attach the event handler, and function we want to assign to it, this can be done like so:
In the demo I’ve setup, you’ll see the existing list of items, give one or two a click and watch the text change and a nice icon appear. Voila! Now, the next step is to create your own element, which I’ve created a nice little script and small form to do exactly that. Simply type a word into the field input, and generate your element. The newly created element will be born with its onclick function attached.
Keeping functions outside the loop
JSLint likes to remind everyone that you shouldn’t create functions inside a loop, in some cases it’s okay to do, but for this tutorial I totally agree. It will save us from writing duplicated markup when running the function on both the static and dynamically created elements (which is why dynamicEvent is created outside the loop and simply called).
For anyone interested to see how the demo works, utilising the steps above, you can have a look through this and the comments: