Reputation: 13400
I need to set focus on input and textarea elements of a sortable list.
Here is my code (1).
a) When I load the list it works fine because it adds a listener for each input.
b) When I add a new element to the list it duplicates the listeners.
How should avoid this?
Maybe trying to use a single listener on body using event delegation?
Any ideas?
thanks
(1)
setTimeout(function () {
var setFocus = function () {
$('.ui-sortable').find('input, textarea').click(function () {
$(this).focus();
});
};
$('.ui-sortable').on('DOMNodeInserted', setFocus);
setFocus();
}, 0);
Upvotes: 2
Views: 1608
Reputation: 14318
This should work:
$('body').on('.ui-sortable input, .ui-sortable textarea', 'click', function () {
$(this).focus();
});
Upvotes: 2
Reputation: 55750
Try delegating the event .. So that you do not need to assign the event every single time you create a new element
$(document).on('DOMNodeInserted', '.ui-sortable', setFocus);
Upvotes: -1
Reputation: 14524
You should either modify your code to only add the listener once, or remove the old listener first:
$('.ui-sortable').off('DOMNodeInserted').on('DOMNodeInserted', setFocus);
If you have other listeners you don't want to remove, you can use the namespace feature when you add the listener, so that you can only remove the listener you're interested in:
$('.ui-sortable').off('DOMNodeInserted.setFocus').on('DOMNodeInserted.setFocus', setFocus);
Upvotes: 0
Reputation: 207511
You can remove it and add it again
$('.ui-sortable').off('DOMNodeInserted').on('DOMNodeInserted', setFocus);
You can try adding it like this
$(document).on('DOMNodeInserted', '.ui-sortable', setFocus);
Upvotes: 0