I am trying to write a small demo which will maintain a fixed number of items in a list which is being constantly updated.
This is my very first attempt at using jQuery, so I would appreciate feedback on if I can improve the code (almost surely!) and also, I am stuck on the last function truncateItems() and would appreciate some help on how to implement it.
Here is what I have written so far:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div>
<div id="container"></div>
</div>
</body>
<script type="text/javascript">
/* <![CDATA[ */
var maxitems = 10; // maximum number of items in container
function generateItems(){
var min = 0;
var max = 10;
var items = '';
var randnum = Math.floor(Math.random() * (max - min + 1)) + min;
for (i=0; i < randnum; i++){
if (i)
item += '\n<div class="item">Item number: ' + i + '</div>';
else
item = '<div class="item">Item number: ' + i + '</div>';
}
addItems(items);
truncateItems(items);
window.setTimeout(generateItems, 1000)
}
function addItems(items){
return items + '\n' + $("#container").text();
}
function truncateItems(items){
//Need to return the first N elements
//Need to either parse items or iterate over them whilst building a new string ? ...
}
$(document).ready(function(){
window.setTimeout(generateItems, 5000); // wait for 5 secs before starting updates
});
/*]]> */
</script>
</html>
In case what I am trying to do is not clear from the code above, this is what I’m trying to do:
- Generate a random number of items
- Update the ‘list’ of items (held in element with id ‘container’). The update should be done so that the latest generated data are placed BEFORE the older items that were in the list (so visually, they appear ‘on top’)
- Ensure that element with id ‘container’ has no more than 10 items in it at any time – with only the LATEST (i.e. TOPMOST) 10 items being left in the ‘list’
Not really sure what your looking for, but try this : http://jsfiddle.net/x36Bm/1/