Alright, here is my javascript:
$().ready(function (){
$(".contact").hover(function (){
...
});
$(".contact").not('.contact[id="'+activeId+'"]').click(function (){
...
});
$(".contact_chooser_contact").click(function (){
...
$('.contacts').append('<div class="contact" id="'+id+'" title="'+phone+'">\
<div class="contact_img"><img src="src/default_face.png" width="64"/></div>\
<div class="contact_info" id="'+name+'">'+name+' <span class="sms_number">0</span></div>\
<div class="contact_last_sms">\
\
<!-- span class="last_sms_time"> echo $message[sizeof($message)-1]->time; </ -->\
</div>\
</div>');
...
});
});
Notice, how in the “contact_chooser_contact” click handler, I append another “.contact” in “.contacts”, but now when I hover over that new “.contact”, it doesnt do anything like it is supposed to. How can I fix this problem, I understand that its because I havent reinitiated the ‘$(“.contact”).hover()’ after I added the new “.contact”, but is there an easier way?
You need to bind the event with on(), using this will bind any element added to the DOM with the respective selector. The advantage of using
on()overlive(), is that you can narrow down the context to a specfic container, rather than the entiredocument. In my example, I just use thedocumentas the context.jQuery 1.7 use on()
Less than 1.7, use delegate()
Less than 1.4.2, use live()