1

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.

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • possible duplicate of [jQuery – on('click') append doesn't seem to work](http://stackoverflow.com/questions/14133570/jquery-onclick-append-doesnt-seem-to-work) – Barmar Jan 04 '13 at 16:38

4 Answers4

5

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)

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

use on()

$('ul#showUsernames').on('click', 'li', function () {
bipen
  • 36,319
  • 9
  • 49
  • 62
0

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 () {
Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48
0

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.

semir.babajic
  • 731
  • 3
  • 9