Append Content On Random Location With Jquery?
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
Solution 1:
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?
Solution 2:
Try something like this:
var randomNum = Math.floor(Math.random()*9);
$(".itemlist li").eq(randomNum).append("HI");
Just create a random number in javascript. Then select that random element in the list and append the new content. Unless I am not understanding the question.
Solution 3:
with accepted answer a new element never gets inserted as first. the position where it can be inserted is number of elements plus one. between elements + beginning + end.
the code is not really nice but fixes it.
var $lis = $(".itemlist li");
var pos = Math.floor(Math.random() * ($lis.length + 1)) - 1;
if(pos != -1){
$lis.eq(pos).after("<li>new</li>");
} else{
$lis.eq(0).before("<li>new first</li>");
}
Post a Comment for "Append Content On Random Location With Jquery?"