Add content at random with jQuery?

I need to display a list of items on a page, and this page is updated using AJAX. Every time a new item is passed to the client, I want it to appear in a random place inside my ul list .

Here is an example of the list I'm talking about: http://jsfiddle.net/XEK4x/

HTML

 <ul class="itemlist"> <li>Item #2</li> <li>Item #2</li> <li>Item #3</li> <li>Item #4</li> </ul> 

CSS

 .itemlist li{ width:100px; height: 100px; margin: 8px; padding: 4px; float: left; background: #dddddd; } 

Any ideas on how to add new items to a random location in a list using jquery? I know that I can do something like $(li_element).appendTo(".itemlist"); but this will add it to the bottom of the list.

Another problem that may be the problem is that each li element moves to the left. Therefore, when a new element is added in the middle, everything after this element will be pressed one place to the right.

I could go with several ul lists floated left and li stacked under each other , so when the new item is rendered, the list will just be pressed down, but if I do it at random, some ul lists may get more than others, which also will look strange.

+4
source share
3 answers
 var $lis = $(".itemlist li"); $lis.eq(Math.floor(Math.random()*$lis.length)).after( /* your new content here */ ); 

Method . after () adds a sibling, so select a random element from the list of <li> elements and use .after() in the subject. Or .before() .

PS As for the recently added element pushing the rest to the right, why is this a problem? Isn't that ok if you have a horizontal layout for your list?

+7
source

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 this random item in the list and add new content. If I do not understand the question.

+2
source

with the accepted answer, the new element will never be inserted as the first. the position at which it can be inserted is the number of elements plus one. between elements + start + end.

the code is not very nice, but fixes it.

http://jsfiddle.net/XEK4x/38/

 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>"); } 
+2
source

Source: https://habr.com/ru/post/1379561/


All Articles