Reputation: 791
I have an array of objects that I grab images from and display on the page, only once displayed, the last one is showing first, and the first one is last - backwards. If I use .append() then it's in the right order but semantically I need to use .prepend() so that my html elements display correctly. Any suggestions on what's going on? I am not able to find anything online as to what's causing this. A link to the doc describing this behavior would be great too!
Here's the jQuery code:
for (var i = 0; i < skills.length; i++) {
var icon = '<img id="' + items[i].id + '" class="item-img-lg" data-toggle="modal" data-index="'+ i +'"src="' + items[i].iconurl + '" />';
$('#items-large').prepend(icon);
};
Upvotes: 0
Views: 503
Reputation: 2206
Prepend isn't reversing the array. During the first loop, your first skill is added to the front of your #items-large. Which is good, because you probably want that first one to be the first icon on items-large! However, during the second loop, the second icon is added to the front (prepended) to #items-large. Ah! Now the first icon is actually the last, and the second icon is the first! This repeats for all of your icons and, in the end, your last icon in the array is in front, or first, and the first icon in the array is in back, or last.
And depending on what else is in #items-large, you may not want to use append, either.
Imagine the following:
<div id="items-large">
<!-- prepended icons go here -->
<h1>My awesome icons</h1>
<!-- appended icons go here -->
</div>
And appending would still result in the same incorrect order of icons!
You're smart enough to figure out what to do from here, but if you need a solution:
You could reverse your icons in the array by hand, or you could call reverse() on your array before you begin prepending them.
Upvotes: 1
Reputation: 33933
You can "reverse" the elements in an array using the .reverse()
method.
Then use .append()
.
// Reverse the array order
items = items.reverse();
for (var i = 0; i < skills.length; i++) {
var icon = '<img id="' + items[i].id + '" class="item-img-lg" data-toggle="modal" data-index="'+ i +'"src="' + items[i].iconurl + '" />';
$('#items-large').append(icon);
};
Upvotes: 0
Reputation: 142
Instead of incrementing could you try decrementing your loop or array.reversing it if you choose to still increment the loop?
Upvotes: 0