1

UPDATE: A commenter told me to change some codes, this is the new code and its not working neither.

I'm creating a Facebook-Like chat. It gets the latest messages "Not Read" from a JSON file and it appends the text to an "UL" element vía "LI" into a box. If the box doesn't exist, it creates and attach the text. I want that when I click that div, it hides using margin-bottom negative, and when I click it again it shows by Margin-Bottom:0. Please help me since it's just not working.

function showChat(id){
$(this).animate({marginBottom : "0"}).removeClass("hidden_box").addClass("active_box").removeAttr('onclick').click(function(){
       hideChat(Id);
    });

}
function hideChat(id){
$(this).animate({marginBottom : "-270px"}).removeClass("active_box").addClass("hidden_box").click(function(){
       showChat(Id);
    });

}

function getOnJSON(){

//Creating Variables that will be used
var from;var to;var msg_id;var msg_txt;

//Getting the data from the json file
$.getJSON("/ajax/chat.json.php",function(data){

//Repeat for each result
$.each(data.notif, function(i,data){

//Getting a var to info
from = data.from;to = data.to;msg_id = data.id;msg_txt = data.text;

//check if div exists
        if ($("#chat_"+from+"_lp").length === 0){

//If not, create the div
            $("#boxes").append('<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"></div>');

//Add the senders name
            $("#chat_"+from+"_lp").append('<div id="'chat_+from+'_nick" class="chat_name">'+from+'</div>');

//Add the chats UL
            $("#chat_"+from+"_lp").append('<ul id="chat_'+from+'_txt" class="chat_txt"></ul>');

//Add the message text
            $("#chat_"+from+"_lp").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');

//Add event handler for each div
            $('#chat_'+from+'_lp').click(function() {showChat(this);});

//If div exists just add the text
        }else{

//Add the message text
            $("#chat_"+from+"_txt").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');

//Add event handler for each document
            $('#chat_'+from+'_lp').click(function() {showChat(this);});

//Close If
        }
//Close data for each item      
    });

//Close JSON
});

//Close Function
}

UPDATE 2: in order to stop making and appending things, I made an unique HTML string that is going to be appended.

new_chat_string = '<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"><div id="'chat_+from+'_nick" class="chat_name">'+from+'</div><ul id="chat_'+from+'_txt" class="chat_txt"><li id="' + msg_id + '">'+ msg_txt+'</li></ul></div>';

$("#boxes").append(new_chat_string);    
Luis
  • 1,067
  • 1
  • 14
  • 25
  • 1
    possible duplicate of [Why doesn't $().click() work on
  • generated by pageinit?](http://stackoverflow.com/questions/9068879/why-doesnt-click-work-on-li-generated-by-pageinit)
  • – PeeHaa Feb 11 '12 at 16:43