Insert A Div In A Random Location In A List Of Divs
Solution 1:
Try something like below,
var $items = $('#container').find('.item');
var pos = Math.floor(Math.random() * $items.length)
$('.randomDiv').insertAfter($items.eq(pos));
Solution 2:
I'd suggest, pending further information:
$('.item').eq(
/* I'm using the eq() method to select a specific element,
and creating the random number (in the range from 0-(number-of-elements))
within the method to avoid creating unnecessary variables. */Math.floor(Math.random() * $('.item').length)
/* after() creates an element from the html string, and inserts it after
the element selected earlier with the eq() method */
).after('<div class="random"></div>');
A slightly altered, though more verbose, alternative to the above:
$('<div />', {
'class': 'random',
'text': '...'
}).insertAfter($('.item').eq(Math.floor(Math.random() * $('.item').length)));
References:
Solution 3:
Code:
HTML:
<div id="container">
</div>
JS:
$(document).ready(function(){
for(var i =1; i<10; i++) {
$("#container").append("<div class='item' id='"+i+"'>Item</div>"); /*adding item divs dynamically */
}
/*the real magic is below */var rand_id = Math.floor((Math.random()*10)+1); /*generating an item divs ID randomly */
$("#"+rand_id).after("<div class='randomDiv'>Random DIv</div>"); /*adding the random div after that div of the rand_id */
});
Fiddle: http://jsfiddle.net/mareebsiddiqui/ULcTc/
Explanation:
This is simple. First I add the item
divs dynamically by giving them ID's respectively with starting from 1 and ending on 10. Then I generate a random ID using Math.floor()
and Math.random()
JavaScript functions. Then I fetch(using a simple technique) the div with that random ID and then after that div I add a random div.
Solution 4:
I will not provide code if you tried nothing.
But if you don't know where to start and need a workflow :
Coun't the number of div in container Create a random number between 0 and the number of div.
Append your div after the div with the random number index.
Solution 5:
This will work:
functionrandomDiv() {
var divCount = $(".item").length;
var randomnumber=Math.floor(Math.random()*divCount);
$("div.item:eq(" + randomnumber + ")").after("<div class='randomDiv'>hey im random</div>");
}
Post a Comment for "Insert A Div In A Random Location In A List Of Divs"