• Register
499 points

Event binding on dynamically created elements javascript

Event binding refers to telling the browser that a particular function should be called whenever some 'event' occurs. Events mostly relate to user input, such as clicks.

An example of binding to an event in jQuery can be the following:

$("#elem").bind("click", function() {

This binds a function to click event of DOM object with identifier elem. When user clicks it, an alert (message box) will be shown. Binding is done by invoking the jQuery bind function but there are other means to do that, (e.g. jQuery click function in case of binding to click event).

When you perform an action on a web page, it will trigger an event. This might be something like:

  • Click a button
  • Select a value from a drop down
  • Hover the mouse over an item

These events can be captured in your JavaScript code.

A common (and often misguided) way of capturing events is to do so on the HTML element itself (as shown in the onclick attribute below)

<input id="MyButton" type="button" value="clickme" onclick="Somefunction()" />

So, when the user clicks the button, the SomeFunction function will be executed.

However, it is considered a better approach to adopt a technique called 'late-binding'. This ensures that your HTML and JavaScript are kept completely separate.

So, we can modify the above exmample like so:

document.getElementById("MyButton").onclick = function(){
   //functionality here.

jQuery makes this even easier:

    //functionality here.
Our Soution:

This is a pure JavaScript solution without any libraries or plugins:

document.addEventListener('click', function (e) {
    if (hasClass(e.target, 'bu')) {
        // .bu clicked
        // Do your thing
    } else if (hasClass(e.target, 'test')) {
        // .test clicked
        // Do your other thing
}, false);

where hasClass is

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;

1 Comment

Wow! Very nicely explained. I was having difficulty in understanding this topic. You explained it so nicely and in easy words.