S. McGrady
S. McGrady

Reputation: 25

How add a div inside Another div but in a random position

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

Upvotes: 0

Views: 1768

Answers (2)

Alnitak
Alnitak

Reputation: 339927

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.

Upvotes: 3

Danil Speransky
Danil Speransky

Reputation: 30463

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);

Upvotes: 0

Related Questions