tags:

views:

471

answers:

5

In my application I have a drop-down form that fires up an AJAX request onchange and returns the selected user name value with a "delete" image next to it.

<div id="el">User Name <img src="ico/del.gif" onclick="ajax_delete(12)" class="del" /></div>

Strangely if the page was loaded for the first time, the following jQuery code is executed correctly and the mouse pointer changes over all .del images:

$("img.del").css('cursor', 'pointer');

BUT, if the html code above is added by the AJAX request like this:

$("#el").html('User Name <img src="ico/del.gif" onclick="ajax_delete(12)" class="del" />');

the mouse pointer change doesn't work for the images added by the AJAX request.

Any clue why?

A: 

You need to use live events.

http://docs.jquery.com/Events/live

When you bind events using the normal method, they are bound to only existing items. Any items created on the DOM after that are not affected.

Matt
The documentation for live documentation specifies it only works with events (click etc..), see documentation.
altCognito
A: 

Maybe live () handler will help you. Read about it in docs.

Roman
live does not support change
Chad Grant
+4  A: 

The element didn't exist at the time you ran the css function. You have to run the css function after it was appended to the DOM.

From the live documentation:

.live doesn't support the no-event style callback that liveQuery provides. Only event handlers can be bound with .live.

You'll need to use the liveQuery plug-in to accomplish this.

It's pretty straightforward from there:

$('#el').livequery(function() {
  $(this).css('background', 'green');
});

Note that liveQuery can also fire for elements which have been removed or no longer match (say if you are matching based on a value comparison) by using the second parameter:

The unmatchedFn is fired when an element changes and is no longer matched or removed from the DOM.

Nice.

altCognito
+2  A: 

$("img.del") returns a selection set of all images currently in the document with a ClassName equal to del. You insert a new element just after that command is called. Therefore you will need to use live events

Huppie
The documentation for live documentation specifies it only works with events (click etc..), see documentation.
altCognito
A: 

In my organisation we have a blog where we share new findings, i recently wrote a blog on this same topic http://spreadyourwealth.blogspot.com/2009/04/jquery-events-not-firing-for-dynamic.html

Fermin