Prior to this revision, I was trying to duplicate one specific node among a few others but I was having undesired duplications
var data = {
"id": "1",
"username": "user5613506",
"data": {
"items": [
{
"id": 1,
"name": "Item #1",
"picture": "assets/images/thumbnails/item1.jpg",
"group": "group1",
"amount": 2,
},
{
"id": 2,
"name": "Item #2",
"picture": "assets/images/thumbnails/item2.jpg",
"group": "group2",
"amount": 3,
}
]
}
};
var index = 0;
$( 'button' ).click( function() {
index++;
if( index >= data.data.items.length ) index = 0;
var $elements = $( '#elements' );
var $icon = $elements.children( 'img.' + data.data.items[ index ].group ).slice( 0, 1 );
$elements.children( 'img' ).addClass( 'hidden' );
for( var i = 0; i < data.data.items[ index ].amount; i++ ) {
$icon.clone().removeClass( 'hidden' ).appendTo( $elements );
}
});
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="elements">
<img src="http://i.imgur.com/TuHUIAC.gif" class="group1 hidden" />
<img src="http://i.imgur.com/dUeBcoU.png" class="group2 hidden" />
</div>
<button>Click Me</button>
Also on JSFiddle ;)
With some comments below the code is not based on the classes available anymore (see revisions if you're curious ^_^).
In the older versions when the <button>
was clicked the first time, and thus the pointer defined by the index
variable was pointing to the second entry of the JSON, everything was working fine.
When the button was clicked one more time, instead of hide/remove the elements previously added, the new ones were being added along of them. Because of this, ever consecutive click was accumulating nodes, breaking the whole layout with the progressive duplication.
Now, before anything, I hide all nodes by adding the hidden class to them all. Then, with a more efficient set of selectors, I find the only image with a specific class that matches some value in the JSON and then I clone it as many times as need, removing the hidden class before append it to the parent node.
However, and now comes the new issue, for now I'm having to use jQuery.slice() to get the first and only the first matching node to serve as base for cloning because, although working, all nodes are still in the DOM when they're hidden.
This is not a problem in this example, with only two entries in the JSON, but when that entry becomes larger, maybe with hundreds of items and, for some odd reason, the user decide to click indefinitely the button, the DOM might get too crowded, which might crash the browser with a memory overflow.
How could I solve that part then?