Based on Insert a div in a random location in a list of divs -- I'm trying to randomly insert some cat photos into a div of non-cat photos:
http://jsfiddle.net/frank_o/QXdL3/21/
But is there a way to prevent the cats from appearing next to each other sequentially? They should be spread out.
JS:
var insertionTemplate = $('.template').find('.image').html(),
insertionTargetChildren = $('.main').find('.image'),
insertionFrequency = 3;
var random;
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
insertionTargetChildren.eq(random).append(insertionTemplate);
}
HTML:
<div class="template" style="display: none;">
<div class="image">
<img src="http://placekitten.com/75/150" />
</div>
</div>
<div class="main">
<div class="image">
<img src="http://lorempixel.com/75/150" />
</div>
<!-- ... -->
</div>
You can shotgun the list, like the above answers, but this is a bit more efficient since you only need to inspect the precise objects you are inserting against, rather than inspecting every image.
Add 2 steps. The first should shuffle the array of images so that they're in a different order every time. The second should create an array of insertion points into the other list. If you don't want cat images to be next to each other, then make sure your list of insertion points, is at least spaced by 2.
You should also use
<script type="text/template">
tags for your templates.http://jsfiddle.net/kf2zU/1/
HTML
JS
Within your loop you could check to see whether the number generated is equal to the last number that was generated +-1
DEMO http://jsfiddle.net/QXdL3/22/
I've fixed the issues and made a check to see if the next or previous element is a cat.
FIDDLE