0

I am creating divs dynamically and would want them added to the parent div in random positions not in the last position e.g.

                        var opt = document.createElement("div");
                        var txt = document.createTextNode(str);
                        opt.appendChild(txt);


                        //get the top and left positioning of the elements
                        var x = Math.floor(Math.random() * (400));
                        var y = Math.floor(Math.random() * (50));

                        opt.style.top = y + "px";
                        opt.style.left = x + "px";
                        opt.style.zIndex = zindex;   

                        $("#parentDiv").append(opt);

But problem is jquery's append function or add function puts the div in the last position on the stack. i want it put randomly between other divs...help

S. McGrady
  • 25
  • 1
  • 5
  • Do you mean that the div you last added lays 'on top of' the others or do you mean that the last added div gets added to the end of the document? – Tom Naessens Aug 23 '12 at 11:12
  • Exact duplicate - http://stackoverflow.com/questions/8002627/append-content-on-random-location-with-jquery – Dipak Aug 23 '12 at 11:15
  • try to add opt.style.position="relative"; – Sora Aug 23 '12 at 11:18

2 Answers2

3
var $parent = $('#parentDiv');
var $children = $parent.children();             // get possible children
var n = $children.length;                       // there are n children
var pos = Math.floor((n + 1) * Math.random());  // and n+1 insert points

if (n === pos) {
    $parent.append(opt);                        // append after last
} else { 
    $children[pos].before(opt);                 // or insert before
}

EDIT I cleaned this up to merge together the no-children / last child case.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    @S.McGrady but you accepted the other answer?! [which is incomplete, wrong, and also violates the DRY principle by calling `$('#parentDiv')` or `$('#parentDiv div')` at least three times?] – Alnitak Aug 23 '12 at 12:53
0

If there is already div:

var i = Math.round(Math.random() * $('#parentDiv').length);
if (i != $('#parentDiv div').length) $('#parentDiv div').eq(i).before(opt);
else $('#parentDiv div').eq(i - 1).after(opt);
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79