Reputation: 7104
I have an jQuery ajax form. When it's completed, it changed the ID of an element like this:
jQuery('#ready').attr('id','done');
Then, I want to do a mouseover()
function targeting #done
. The problem is that it does not work because #done was not loaded on page load.
What is the normal solution to this issue?
Upvotes: 1
Views: 1909
Reputation: 7878
You need to use event-delegation for this:
$(document).on('mouseover', '#done', function(){
//do something
});
You're appending content to your DOM after the event-listener for your mouseover on #done
is registered. So this element does not exist at the time your binding an event to it.
Through event-delegation you are able to bind an event-listiner to an existing parent (document
in this case). And this will listen to all events of its descendants matching the #done
- selector.
Upvotes: 4
Reputation: 27765
You need to use this approach:
$( document ).on( 'mouseover', '#done', function() {
//...
});
In this case your function handler will be attached to document
and on mouseover
it will search for #done
element to fire.
Upvotes: 2