Highlighting Words With Javascript, What Am I Missing?
I have been working with a basic javascript/PHP chatroom. I want certain words to be highlighted as they appear in the chat stream. The html output for the chatroom looks like: &l
Solution 1:
If you want your highlighting code to run after an AJAX call has returned (when there are new HTML fragments), then try something along these lines:
$.ajax({
...
success : function(data) {
...
$('.chat').each(function(){
var hashtag = $(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
$(this).html(hashtag);
});
},
...
});
In your case, call your highlighting code after you have populated all your chat fragments:
...
function (response) {
chats = jQuery.parseJSON( response );
if ( chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
// Call highlighting code here
}
}
...
PS You can save time by caching the selector jQuery('div.chat-container')
as a variable so that jQuery doesn't have to search your HTML each time.
Post a Comment for "Highlighting Words With Javascript, What Am I Missing?"