Mr_Green
Mr_Green

Reputation: 41832

click event of jQuery doesnt work for dynamically generated li

Can someone please have a look at this code in which every function works perfect but only the click event (which is at last of the code)

 $('ul#showUsernames li').on('click', function () {
    selectedUsername = $(this).text();
    if (selectedUsername != chatUsername) {
        chatTitleName.text("Chat between " + chatUsername + " and " + selectedUsername);
    }
 });

Here I used .click and also bind('click',function they too didnt work.

I am using on here because I am generating the li elements dynamically through jQuery.

I am not sure whether this matters here or not that I am using SignalR in my project.

Please help.

Upvotes: 1

Views: 960

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

use event delegation with on()

$('#showUsernames').on('click', 'li', function () {
   ...

this will work also for dynamically inserted list-items and it will be more performant (since you're attaching a single event handler on your ul instead of n handlers on the li elements.

As a sidenote just use $('#showUsernames') instead of $('ul#showUsernames') since it's faster (it's like a straight getElementById)

Upvotes: 5

semir.babajic
semir.babajic

Reputation: 741

Use live()

Example:

$(".button").live("click", function() {
});

Make sure to call die() as well, like this:

$(".button").die();

die() will prevent your event from firing multiple times. This scenario would occur in case your content is being asynchronously loaded multiple times without a synchronous reload of entire page. This is because the old handlers remain in browsers memory, and they get fired as well (simple explanation).

Hope it helps.

Upvotes: 0

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

you can use Jquery Live

$('li ul#showUsernames').live('click',function () {

can use on also as live is depricate ( thanks to @Mr_Green )

$('ul#showUsernames').on('click', 'li', function () {

Upvotes: 0

bipen
bipen

Reputation: 36531

use on()

$('ul#showUsernames').on('click', 'li', function () {

Upvotes: 2

Related Questions