Mark Boulder
Mark Boulder

Reputation: 14297

Insert div into random location inside a container of divs

How do I insert a div into a random location inside a container of divs? Similar to Insert a div in a random location in a list of divs except I'm not using a list.

Right now it appears inside a random container div, not randomly inside the container itself:

http://jsfiddle.net/frank_o/QXdL3/15/

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 class="image">
    <img src="http://lorempixel.com/75/150">
  </div>
  <div class="image">
    <img src="http://lorempixel.com/75/150">
  </div>
</div>

JS:

var template = $('.template').find('.image').clone(),
  target = $('.main'),
  targetChildren = target.find('.image'),
  random = Math.floor(Math.random() * targetChildren.length);

targetChildren.eq(random).append(template);

Upvotes: 2

Views: 1168

Answers (3)

Fizzix
Fizzix

Reputation: 24375

You were very close!

Instead of .clone(), try using .html() like my example below.

Also, I slightly changed your loop along with the random number generator.

Works very well now. Refresh the page to see three random kitty photos added somewhere within the other images.

WORKING EXAMPLE

Upvotes: 1

juvian
juvian

Reputation: 16068

This will put it in random position:

random = Math.floor(Math.random() * (targetChildren.length+1));
if(random > targetChildren.length){
   target.append(template);
}else{
    targetChildren.eq(random).before(template);
}

The targetChildren.length+1 is to add the possibility of appending in the last place ;)

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

You're almost there. You just need to change append to after; change:

insertionTargetChildren.eq(random).append(insertionTemplate);

To:

insertionTargetChildren.eq(random).after(insertionTemplate);

Your current code inserts the new div into another div as follows:

<div class="image" style="position: absolute; left: 150px; top: 310px;">
    <img src="http://lorempixel.com/75/150">
  <div class="image" style="position: absolute; left: 225px; top: 310px;">
    <img src="http://placekitten.com/75/150">
  </div>
</div>

The new version will produce the following:

<div class="image" style="position: absolute; left: 150px; top: 310px;">
    <img src="http://lorempixel.com/75/150">
</div>
<div class="image" style="position: absolute; left: 225px; top: 310px;">
  <img src="http://placekitten.com/75/150">
</div>

Upvotes: 2

Related Questions