Binding Click Event to a Dynamically Created Element using jQuery

In jQuery, you can use the .click() method to trigger a click event. This method works with almost every element. However, the .click() method does work on elements that you will create dynamically using a script. Here, in this post I’ll explain with examples on how to bind click event to a dynamically created element using jQuery.

Let me first explain how you can use the .click() method to trigger the click event. I have a <div> element on my web page and I can easily bind a click event to it. Although, we often use <div> element as a container, we can add an event to it.

The Markup
<div id="main"> Click Me </div>

Now let’s bind the element to the .click() method.

The Markup and GridView
<script>
    $(document).ready(function () {
        $('#main').click(function () {
            alert('Success');
        });
    });
</script>

Try it Yourself

Click the below DIV element

Click Me

Simple isn’t it. The .click() method works fine with the <div> element, since the element was present when page was loaded, and it is now DOM ready. See, I have attached .click() inside the .ready() method.

However, this method does not work with dynamically created elements. To add an event dynamically to an element, you’ll have to use jQuery .on() method, using a process called Event Delegation.

Event delegation allows us to add events to descendant elements (such as child, grandchild, and great grandchild etc.) that we add to a parent element, at a later stage or at run time.

Now, let’s create a dynamic element, attach it to our parent element (that is main <div>) and finally attach a click event to it using the .on() method.

Syntax of jQuery “.on()” Method

$(element).on(event, childSelector, data, function)

The Markup
<!DOCTYPE html>
<html>
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div id="main"> 
        </div>
</body>
The Script

I would create a <span> element in my script, and add the element to the <div>. Next, I’ll use the .on() method to add an event (click in our case) to the <span>, which is a descendant (child) of the <div> element.

<script>
    $(document).ready(function () {
        var divMain = document.getElementById('main');

        for (i = 1; i <= 5; i++) {
            var divCount = document.createElement('div');

            divCount.innerHTML = '<span class="counter" id=' + i + '>' + i + '</span>';
            divMain.append(divCount);
        }

        // ATTACHED A 'click' EVENT TO EVERY SPAN, WHICH IS A DESCEDANT OF DIV 'main'.
        $('#main').on('click', 'span', function () {
            $(this).css({ 'backgroundColor': '#F00', 'color': '#FFF' });    // CHANGE THE CSS.
        });
    });
</script></html>

Try it Yourself

5 Dynamically created SPAN elements, each attached with the Click event. Click the elements.

Any <span> element that we add to the <div> now has a click event attached to it. In the above example, I have used the span keyword as childSelector to the .on() method. See the syntax above.

Passing Class Name as childSelector to the .on() Method

You can pass a class name as parameter to the childSelector property of the .on() method. Now, in many case you might have the same element (say <span>) performing different functions, based on some conditions. To which you might add different class name to the elements.

In the above example, I have added a class name called counter to each dynamically created <span> element. I can use the class name for the childSelector parameter.

<style>
    .counter, .no_counter {
        position:relative;
        float:left;
        width:20px;
        height:20px;
        border:solid 1px #EEE;
        text-align:center;
        padding:3px;
        margin:1px;
        cursor:pointer;
        color:#1464F4;
    }
    .no_counter {
        color:#999;
        cursor:default;
    }
</style>

$(document).ready(function () {
    var divMain = document.getElementById('main');

    for (i = 1; i <= 5; i++) {
        var divCount = document.createElement('div');
        if(i == 2)
            divCount.innerHTML = '<span class="counter" id=' + i + '>' + i + '</span>';
        else
            divCount.innerHTML = '<span class="no_counter" id=' + i + '>' + i + '</span>';

        divMain.append(divCount);
    }

    // ATTACHED 'click' EVENT ONLY TO A PARTICULAR CLASS (NOT EVERY SPAN).

    $('#main').on('click', '.counter', function () {
        $(this).css({ 'backgroundColor': '#F00', 'color': '#FFF' });
    });
});

Note: The class name counter, is prefixed with a dot “.”.

The result is the same, just like the first example.

Try it Yourself

Attached Click Event to Elements with a Particular Class

That’s it. Thanks for reading.

Previous - Dynamically Add Textbox and Button using jQuery and Save Data to an SQL Server Table using a Web MethodNext - Dynamically Bind or Populate SELECT Dropdown List with JSON Data using jQuery Ajax



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!