Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append won't call twice?

var random1 = Math.floor((Math.random()*elems.length));
var random2 = Math.floor((Math.random()*elems.length));

while (random1 == random2) {
    var random2 = Math.floor((Math.random()*elems.length));
}

$j('#project-scroller').append( elems );
$j('#project-scroller').append( elems[random1] );
$j('#project-scroller').append( elems[random2] );

So here's what's happening: elems gets appended but elms[random1] and elems[random2] doesn't.

So then I tried this instead:

$j('#project-scroller').append( elems );
$j('#project-scroller').append( elems );

And elems was only appended once, that time, too! So then I tried this instead:

$j('#project-scroller').append( elems[random1] );
$j('#project-scroller').append( elems[random2] );

And both random elems were appended. Then I tried appending random1 twice, and it was only appended once...

What am I missing? Why won't jQuery append the same elements more than once? Tried the same thing with appendTo (just for kicks), and it does the same thing.


Thanks for the answer! Here's what I ended up with:

var random1 = Math.floor((Math.random()*elems.length));
var random2 = Math.floor((Math.random()*elems.length));
while (random1 == random2) {
    var random2 = Math.floor((Math.random()*elems.length));
}
newElem1 = $j(elems[random1]).clone();
newElem2 = $j(elems[random2]).clone();
$j('#project-scroller').append( elems ).append( newElem1 ).append( newElem2 );
like image 743
Luke Carbis Avatar asked Feb 21 '23 13:02

Luke Carbis


1 Answers

It's not appending a copy of elems, it's appending the real thing. Use clone() to create a 2nd copy to append.

like image 129
Craig O Avatar answered Mar 05 '23 03:03

Craig O