jQuery add event handler to dynamically created element

The following example, allows us to dynamically create new list item (li), attach a click event handler and add it to the unordered list (ul). This happens when you click "Add a New List Item" button. The problem with this approach is that we are binding a click event handler to every list item. This means if you have 500 list items, then there will be 500 event handlers in the memory and this may negatively affect the performance of your application. 


<html>
<head>
    <title></title>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('li').on('click'function () {
                $(this).fadeOut(500);
            });

            $('#btnAdd').on('click'function () {
                var newListItem = $('<li>New List Item</li>').on('click'function () {
                    $(this).fadeOut(500);
                });

                $('ul').append(newListItem);
            });
        });
    </script>
</head>
<body style="font-family:Arial">
    <input id="btnAdd" type="button" value="Add a New List Item" />
    <ul>
        <li>List Item</li>
        <li>List Item</li>
    </ul>
</body>
</html>

A better way of doing the same from a performance standpoint is shown below. In this example, the click event handler is attached to the listitem (li) parent element (ul). Even if you have 500 list items, there is only one click event handler in memory. 

So how does this work
1. When you click on a list item (li), the event gets bubbled up to its parent (ul) as the list item (li) does not have an event handler 
2. The bubbled event is handled by the the parent (ul) element, as it has a click event handler.
3. When a new list item is added dynamicaly, you don't have to add the click event handler to it. Since the newly created list item (li) is added to the same parent element (ul), the click event of this list item also gets bubbled upto the same parent and will be handled by it. 

<html>
<head>
    <title></title>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('ul').on('click''li'function () {
                $(this).fadeOut(500);
            });

            $('#btnAdd').on('click'function () {
                $('ul').append('<li>New List Item</li>');
            });
        });
    </script>
</head>
<body style="font-family:Arial">
    <input id="btnAdd" type="button" value="Add a New List Item" />
    <ul>
        <li>List Item</li>
        <li>List Item</li>
    </ul>
</body>
</html>

Comments

Popular posts from this blog

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

jQuery dynamic menu from database in asp.net

Automatically send Birthday email using C#.Net