Reputation:
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?
Upvotes: 2
Views: 2613
Reputation: 2230
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.
Upvotes: 1
Reputation: 41391
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.
.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.
Upvotes: 6
Reputation: 11432
$("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
Upvotes: 3