Qasim
Qasim

Reputation: 1704

jQuery event fails when a new div is added

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?

Upvotes: 2

Views: 364

Answers (2)

weiaijun
weiaijun

Reputation: 1

".contact" add event when the document onload. after, the div added from ".contact" 's event doesn't have event in fact. because the click event don't execute again.

you can do like this:

function addDiv(div) {
    div.hover(function() {
        ...
    });
}

$(function() {

    addDiv($(".contact"));

    $(".contact_chooser_contact").click(function (){
        addDiv($('<div/>').addClass('.contact').attr({id:ID, title: TITLE}).append(...));
    });
});

Upvotes: -1

Gabe
Gabe

Reputation: 50493

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() over live(), is that you can narrow down the context to a specfic container, rather than the entire document. In my example, I just use the document as the context.

jQuery 1.7 use on()

$(document).on('mouseover', '.contact', function(){
  ...
}); 

Less than 1.7, use delegate()

$(document).delegate('.contact', 'mouseover', function(){
   ...
}); 

Less than 1.4.2, use live()

$('.contact').live('mouseover', function(){
   ...
}); 

Upvotes: 4

Related Questions