Binding Click Event to a Dynamically Created Element using jQuery

← PrevNext →

In jQuery, you can use the .click() method to trigger a click event. This method works with almost every element. The .click() method also 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 the click event to it. Although, we often use the <div> as a container, we can add an event to it.

The Markup and the Script
<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div id="divMain"> Click Me </div>
</body>

<script>
    $(document).ready(function () {
        // Bind the DIV element to the .click() method.
        $('#divMain').click(function () {
            alert('Success');
        });
    });
</script>
</html>
Try it

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 Code

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.

<!DOCTYPE html>
<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        .counter{
            font:15px Verdana;
            float:left;
            width:20px;
            height:20px;
            border:solid 1px #EEE;
            text-align:center;
            padding:3px;
            margin:1px;
            cursor:pointer;
            color:#1464F4;
        }
    </style>

    <p>Click the elements.</p>
    <div id="main"> </div>
</body>

<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);
        }

        // Attach a click event to every span inside the DIV.
        $('#main').on('click', 'span', function () {
            $(this).css({ 'backgroundColor': '#F00', 'color': '#FFF' });    // Change its style.
        });
    });
</script>
</html>
Try it

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.

That’s it. Thanks for reading .

← PreviousNext →