Tutorial :Why don't jQuery's event handlers work with changed DOM elements?



Question:

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?


Solution:1

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.


Solution:2

$("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


Solution:3

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.


Solution:4

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »