views:

341

answers:

4

Hi all.

JQuery events are annoying me. The thing is that I very often use javascript (after ajax requests, etc.) to draw up new elements (buttons, divs, etc.). I've got a list of elements which you can press on an edit button so you can manipulate the one linked to the selected edit button.

Now if someone submits a form to make a new element like the ones who existed before, and I submit it with ajax and then I append or prepend the new element into the list. After that the new edit button for the new element isn't linked to JQuery's event system since the DOM hasn't been reloaded after the edit button was made. If I call the same javascript file with the events in it, then the edit button works but then when people click other edit buttons the event happens twice for them since they're bound twice. I've also used .bind() but that only binds (I think) the same event twice as before. I don't remember at the moment how I tested it. I haven't tested .one() but I would rather not use it since some events must be called more than once.

I just wanted to ask you guys what approach you use when dealing with the events?

P.S. I'm binding the JQuery event to the class attribute that all the elements have. If I was going to bind this to each element based on ID, then this wouldn't be a problem because then I would just use .bind(). By writing this I suddenly though of using .unbind() and then .bind() to link the elements to the events system. What do you think of that? Would you do it in another way?

Thanks in advance. Kristinn.

+2  A: 

Your question is a bit general, but I have a feeling that what you're looking for is jquery live

Steerpike
Yes. jQuery.live() acts in the same way as .bind(), except that it will create new event handlers on elements as they are created.
bigmattyh
I'm pretty sure it just attaches one event handler for the event on the document object and parses the event object to detect which element triggered the event.
meder
Thanks a lot for this.
Kristinn Örn Sigurðsson
+4  A: 

You're looking to use $.fn.live:

$('a').live('click', function(e) {
    e.preventDefault();
    alert('im attached even if the DOM has been updated!');
});

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

meder
Thanks a lot for this.
Kristinn Örn Sigurðsson
live() doesn't work with everything. If you want to bind a non-supported event with live(), you're out of luck. What I do in this case is put a .bind() call in my reload() function (which I call after an edit, say). This works really well.
Vince
preventDefault() easily can be replaced by return false; by the way :)
Mushex Antaranian
I find preventDefault to be much cleaner. return false is reliant on being the last statement in the function body also.
meder
A: 

Check the below URL

http://asimsajjad.blogspot.com/2009/01/live-event-in-jquery.html

hope that will help.

Asim Sajjad