jQuery add event handler to dynamically created element

preview_player
Показать описание
Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

In this video we will discuss, how to add event handlers to dynamically created elements. Let us understand this with an example.

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 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 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>
Рекомендации по теме
Комментарии
Автор

Very perfect and precise. I am very much impressed by your vocabulary, right selection of words and you have amazing control on throw of your voice. Wonder how can a human being be so perfect. Thank you Hats off.💯

humhaiihindustani
Автор

you're the great teacher on youtube

NTICTECH
Автор

Great video, helps a lot even after 7 years!

mateogrifsha
Автор

One of the best, sweet and pure VOICE, I come across. Feel like listening more and more. Great job man. All the best.

bimbadigimedia
Автор

The essence of clarity. Most excellent teaching. Thank you.

robinandrews
Автор

I've been looking for this kind of example, but couldn't find the proper way to search for it. Thank you so much!

taokodr
Автор

wonderful, you're a great teacher

malmahsyar
Автор

Thanks u a lot sir ..💯
I am looking this only from 10 days..

davidjonson
Автор

three year old tutorial but still one of best tutorial on YouTube.(:

saurabhrana
Автор

thank u much, was doing my head in, worked out it only happened on newly created li's, searched and searched and found ur video

liamsmith-ypxh
Автор

This was a perfect explanation for this. Awesome!

yourbrainoncode
Автор

Excellent job on this, sir; *thank you!*

billwindsor
Автор

Thankful! helped me out so I can go forward with my cding:)

paalaleksander
Автор

That was an excellent explanation. Thanks you !

aloksingh
Автор

Awesome, I was struggling with this. Very helpful :)

kevinamirdjanian
Автор

Thank you so much.This was very helpful

isunas
Автор

thank you venkat. You solved one of my problem. But I have one small doubt. Is the handler object (Parent UL in your case) should be hard coded element? I am facing a situation in which all elements in that section is dynamically generating. Consider in my case I have to create an load a table element with few data and a button event within its cells through ajax. in this case I think I cannot use the table or any of its child nodes as event handlers because all are generating on the fly. Please let me know Can I use TR in my case as an event handler? or should I use any parent node like a container DIV of the entire table

salamkottayam
Автор

best teacher ...for me its khanacadmy ...

rehmanshahyan
Автор

You're a god! Thanks for the video

MasterZiomekPL
Автор

Hello Venkat,
Thank you for all the Videos and the great job you have done so far. I followed most of the videos in your .Net series.

I have a problem in this session. when I use 'fadeOut' I receive an unhandle exception and the message is: Object doesn't support property or method

How can I solve this?

Thanks

awakeningawarenessfreedom
join shbcf.ru