HomeОбразованиеRelated VideosMore From: kudvenkat

jQuery event delegation

173 ratings | 37969 views
Link for all dot net and sql server video tutorial playlists https://www.youtube.com/user/kudvenkat/playlists?sort=dd&view=1 Link for slides, code samples and text version of the video http://csharp-video-tutorials.blogspot.com/2015/05/jquery-event-delegation.html In this video we will discuss the concept of event delegation in jQuery. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. Both on() and delegate() functions allow us to perform event delegation. How does the following example 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 it's own click 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 explicitly 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. 4. undelegate() stops event delegation <html> <head> <title></title> <script src="jquery-1.11.2.js"></script> <script type="text/javascript"> $(document).ready(function () { $('ul').delegate('li', 'click', function () { $(this).fadeOut(500); }); $('#btnAdd').on('click', function () { $('ul').append('<li>New List Item</li>'); }); $('#btnUndelegate').on('click', function () { $('ul').undelegate('li', 'click'); }); }); </script> </head> <body style="font-family:Arial"> <input id="btnAdd" type="button" value="Add a New List Item" /> <input id="btnUndelegate" type="button" value="Undelegate" /> <ul> <li>List Item</li> <li>List Item</li> </ul> </body> </html> If you are using jQuery 1.7 or higher version, jQuery recommends to use on() to perform event delegation instead of delegate(). The above example can be very easily rewritten using on() and off() functions, instead of delegate() and undelegate() functions as shown below. We discussed performing event delegation using on() function in detail in Part 36 of jQuery tutorial. <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>'); }); $('#btnUndelegate').on('click', function () { $('ul').off('click', 'li'); }); }); </script> </head> <body style="font-family:Arial"> <input id="btnAdd" type="button" value="Add a New List Item" /> <input id="btnUndelegate" type="button" value="Undelegate" /> <ul> <li>List Item</li> <li>List Item</li> </ul> </body> </html>
Html code for embedding videos on your blog
Text Comments (17)
Jesse Gray (2 months ago)
Thank you for your video, I had my selectors the wrong way around on my delegated "on" function until I watched your video
HappyPlaces (2 months ago)
Thank you
Carl Viernes (2 months ago)
Is it possible to re-delegate an event listener? If there was such a term.
aetken (7 months ago)
EVERYTHING SEEMS EASY WHEN EXPLAINED BY YOU SIR. YOU ARE THE BEST OF THE BEST.
Luis Robles (8 months ago)
I like that you have everything written out in the description.
The only reliable tutorial
dyunior (1 year ago)
valuable resources notes, examplesm, infos etc. thank you.
Ahmet Yaman (1 year ago)
thank you sir
Sudhanshu Sharma (2 years ago)
Great Videos @kudvenkat. A quick query, kindly answer please Lets assume we have two webpages viz default.aspx and inventory.aspx and one myScript.js where all jQuery script goes for both webpages. Now i have button with id as btn1 on both pages. So how do i tell jQuery which button is clicked as I can define button click even only once in myScript.js for btn1. Lets assume we can not distinguish the buttons based on selectors. Both buttons have same id, css class etc. One way that is found is to get path for the web page using window.location.pathname, is there is any other way. I want all my jQuery at one place ie. in myScript.js only. Please help.
Enrico Roma (3 years ago)
Best tutorial ever seen. Great!
Srinivas Somasundaram (3 years ago)
Hi Venkat.. I added a delegate button which activates the event delegation upon clicking the button. But I run into an error which says " Object doesn't support property or method 'apply'" on line "ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ).apply( matched.elem, args );" in jQuery.event.dispatch. (jQuery version: jquery-2.1.4.js) Here's the code snippet: <script type="text/javascript"> $(document).ready(function () { $('ul').on("click", 'li', function () { $(this).fadeOut(200); }); $('#delegateButton').click(function () { $('ul').on('click', 'li'); }); $('#undelegateButton').click(function () { $('ul').off('click', 'li'); }); }); </script> </head> <body style="font-family:Arial"> <div> <input type="button" id="delegateButton" value="Delegate" /> <input type="button" id="undelegateButton" value="Undelegate" /> <ul> <li> List Item 1</li> <li> List Item 2</li> <li> List Item 3</li> <li> List Item 4</li> </ul> </div> </body> I would be glad if you could help me figure out why I am seeing this error.
Liam2349 (2 years ago)
Not sure if you figured this out, but in your delegateButton you didn't specify a function. You wrote: $('#delegateButton').click(function () {                 $('ul').on('click', 'li');             }); But you need to include a function as the third parameter, or the click event won't work.
developernader (3 years ago)
Thanks so much Eng Venkat
Dante Vergil (3 years ago)
Hi venkat can please explain what pub/sub and dependency injection in javascript
rakesh sharma (4 years ago)
hello sir,how are u.plz cover the parts which left uncovered,.. angel man(novel man)plz try this. u are a amazing person for me.
Tan YEW MENG (4 years ago)
Happy Labour Day to you sir. I would like to take this opportunity to thank you for the relentless contributions and efforts in recording and uploading all the videos for the benefits of the .NET communities. Your efforts are truly appreciated. Once again all your videos are superb!!!
kudvenkat (4 years ago)
+Tan YEW MENG Hello Edward. Thank you and wish you the same.

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.