1

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?

Henrik Petterson
  • 6,737
  • 17
  • 59
  • 134
  • dont change the elements `id`, use a class instead (`addClass()`, `removeClass()` and `toggleClass()`) – atmd Feb 27 '15 at 15:26
  • You need to use [**Event Delegation**](http://learn.jquery.com/events/event-delegation/). – Satpal Feb 27 '15 at 15:29
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – empiric Nov 30 '18 at 10:45

2 Answers2

3

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.

empiric
  • 7,449
  • 6
  • 35
  • 44
2

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.

antyrat
  • 26,266
  • 9
  • 69
  • 74