I'm using an event to replace "src" attributes in some layers (<div class="total-title" src="anURL">
):
$('.playOnAP').on('click',function() {
$('#mp3-list ul li',this).each( function( index, element ) {
$('.total-title').eq(index).attr('src', $(this).text() );
});
and it works the first time, but not after an Ajax request, when the $('.playOnAP')
elements are replaced. I'm guessing I should use Delegated Events, but don't make myself clear.
I've tried the next:
$('.playOnAP').on('click','#mp3-list ul li',function() {
$('.playOnAP #mp3-list ul li').on('click',function() {
$('.playOnAP #mp3-list ul li').on('click','#mp3-list ul li',function() {
but doesn't work.
You need to put the delegate on a parent of .playOnAp if you are replacing .playOnAp. The event handlers only attach to DOM elements that exist when you add the event handler.
Try this:
When using event delegation, you must bind the event to an element that was originally in the DOM. If something has been dynamically replaced, you cannot bind to that.
As Anup insightfully mentioned, it is not strictly necessary to bind the click event to
document
-- any parent element will do, as long as it was originally in the DOM.For example, if
.playOnAP
is the topmost container element that is being replaced:You could use:
As a default, though, you can pretty much always use
$(document).on()
(even if just as a quick check to make sure everything works before narrowing down to the most appropriate element).