Reputation:
function randomEmoji() {
var emojis = [
':)', ':(', '=D', 'xD', 'o_O', ':|', ':-O', ':$'
];
return emojis[ Math.floor( Math.random() * emojis.length ) ];
}
function textscroll(){
$('.messages').append("<li>" + randomEmoji() + "</li>");
}
setInterval(textscroll,3000);
function scroll(){
$('.messages').children().hide();
}
setInterval(scroll,5900);
As you can see my code appends a random emoji to .messages(an unordered list in my HTML file) every 3 seconds. How can I limit this to show only the 10 most recent emojis? I've tried to hide the list and show it when it adds a new one. Not only does it not do this it would also just keep listing them down the page. I don't know what to do next, this isn't homework or anything actually worthwhile just a weird question thats been driving me crazy the last couple days. Is there anyway besides using .hide() to do this? I feel like using .hide() every 4 seconds is kind of hard on the eyes. I've searched MDN to find something to implement into my code but have had no luck.
Upvotes: 1
Views: 604
Reputation: 836
Try something like this (http://jsfiddle.net/3CBKP/1/):
Every time you add a new list item check the length to see if it is above the limit:
var messageLimit = 10;
function randomEmoji() {
var emojis = [
':)', ':(', '=D', 'xD', 'o_O', ':|', ':-O', ':$'
];
return emojis[ Math.floor( Math.random() * emojis.length ) ];
}
function textscroll(){
var $messages = $('.messages');
var $children = $messages.children();
$messages.append("<li>" + randomEmoji() + "</li>");
if($children.length > messageLimit) {
// there are too many, remove the oldest
$children.first().remove();
}
}
setInterval(textscroll, 100);
Upvotes: 0
Reputation: 1450
Hrm. I think what I would do in this situation is look at the length of the list. If the length of the list is >10. Just remove the first element. If you want to keep track of all the emojis for some reason, but just display the most recent ten, you could have similar logic, but instead of removing the first element, you could select the first item in the list that doesn't have some custom class...say "last10" that you create, and then append that class to the item when you add an item to the list...then you just display all items that have the class "last10".
To be more specific: You'd look for an item that doesn't have the class "last10" append the class, then hide the item.
Upvotes: 0
Reputation: 66981
Right after you append a random Emoji, just check the count of the list items, and if it's above 10 then remove the first one, and you'll be all set.
function textscroll () {
$('.messages').append("<li>" + randomEmoji() + "</li>");
if ( $('.messages li').length > 10 ) {
$('.messages li').first().remove();
}
}
Upvotes: 3