I need to display a list of items in a page, and this page is updated with AJAX. Every time a new item is pushed to the client I want it to appear at a random location inside my ul list
.
Here's an example of the kind of list I'm talking about: http://jsfiddle.net/XEK4x/
<ul class="itemlist">
<li>Item #2</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
</ul>
.itemlist li{
width:100px;
height: 100px;
margin: 8px;
padding: 4px;
float: left;
background: #dddddd;
}
Any ideas how I add new items at a random location in the list using jquery?
I know I can do something like $(li_element).appendTo(".itemlist");
but this will append it to the bottom of the list.
Another thing that might be a problem is the fact that each li element
is floated to the left. So when a new element is added in the middle, everything after that element will be pushed one spot to the right.
I could go with several ul lists floated left
, and the li's stacked under each other
, so when a new item is rendered the list simply get's pushed down, but if I do this at random, some ul lists could get longer than others which would also look strange.
var $lis = $(".itemlist li");
$lis.eq(Math.floor(Math.random()*$lis.length)).after(
/* your new content here */ );
The .after() method appends a sibling, so select a random element from the list of <li>
items and use .after()
on it. Or .before()
.
P.S. Regarding a newly added item pushing the others to the right, why is that a problem? Isn't that normal if you have a horizontal layout for your list?