Reputation: 41832
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
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
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
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