You need to split out the code that does the Ajax call into it's own function. Then, you can call it both from a click and a setInterval like below.
Edit: This is a snippet taken from my fiddle.
Essentially, it wires up each box as it's own chat container, and has an interval timer on each that only updates when the box is visible.
$(document).ready(function () {
var box = $('.box')[0]; //single copy of the target box
$('.contact').click(function () {
var id = $(this).closest('.contact').attr('id'); // load the user id
if ($(".chat-windows").find("#" + id + "-window").exists()) {
if($(".chat-windows").find("#" + id + "-window").is(":visible")) {
//Do nothing, because the window is already there
} else {
$(".chat-windows").find("#" + id + "-window").fadeIn(200).css("display", "inline-block");
}
} else {
//This is a new box, so show it
var newBox = box.cloneNode();
var windows = $(".chat-windows");
$(newBox).find(".chat-header").text(id);
$(newBox).prop("id", id + "-window");
//var username = $(this).find('.username').attr('id');
windows.append($(newBox));
$(newBox).fadeIn(200).css("display", "inline-block");
updateChat({
ContactID: id
});
setInterval(function() {
if($(newBox).is(":visible")) {
updateChat({ContactID: id});
} else {
//do nothing so we aren't updating things that aren't seen and wasting time
} // end if/else
}, 10000); // fire every 10 seconds for this box
} // end if/else
});
$(document).on("click", ".close-chat", function(e) {
$(e.currentTarget).parent().fadeOut(100)[0].removeNode();
});
});
//Global prototype function to determine if selectors return null
$.fn.exists = function () {
return this.length !== 0;
}; // end function exists
function updateChat(args) {
//Do your Ajax here
/*$.ajax({
url: 'ajax/chat.php',
type: 'POST',
data: {
'id': args.ContactID
},
async: false,
cashe: false,
success: function (data) {
$('#chat').html(data);
}
});*/
$("#" + args.ContactID + "-window").find(".messages").append("<li>" + "My Message" + "</li>");
}
I have created a fiddle that demonstrates this here: http://jsfiddle.net/xDaevax/7efVX/
I'm not clear on exactly which parts of your code should go in the ChatFunction, but you should be able to get the general idea from this code and my example regardless of what you are trying to accomplish with the chat.