0

I have an array containing a list of images that I have stored online:

var imgs = ["img1","img2","img3"...];

They are displayed as such:

var child, i;
for (i = 0; i < imgs.length; i++) {

   child.style.backgroundImage = 'url(https://mywebsite/images/' + imgs[i] + '.jpg)';

   $('body').append(child);
}

However, I'm looking to try to display the images based on their attribute, that can change depending on a user action.

This attribute will look like this:

child.setAttribute("class", 0);

Say for example, the user decides to click on an image, then the attribute of the image he clicked on will increment. So the class will no longer be '0' but '1'. And because of so, the image will be placed before the others in the array.

Assuming 'img2' was clicked, then the array would look like:

imgs = ["img2","img1","img3"...];

I feel like the method I'm going by is inefficient and I have considered using objects or even 2d arrays, but I'm not sure where to start and lack experience. However, if this isn't "such a bad way" to get started, then I'd appreciate if someone showed me how I could move the elements in the array.

Thanks in advance.

NotToBrag
  • 655
  • 1
  • 16
  • 36
  • http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another – pawel May 11 '15 at 19:47

2 Answers2

0

You can use array.sort with a compare function. getClass method here is some method which returns current class attribute of an image by it's url

imgs.sort(function(img1, img2){
    var class1 = getClass(img1);
    var class2 = getClass(img2);
    return class1 - class2;
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Dan Prince
  • 29,491
  • 13
  • 89
  • 120
Katya Pavlenko
  • 3,303
  • 3
  • 16
  • 28
0

You can try this:

$('body').find("img").on("click", function() 
{
    $(this).data("count", (Number($(this).data("count")) + 1));  
    reOrderImages();
});

function reOrderImages()
{
    var imgs = $('body').find("img");

    for (var i = 0; i < imgs.length; i++)
    {
        var img1 = $(imgs[i]);
        var img2 = (imgs.length > (i + 1) ? $(imgs[(i + 1)]) : false);

        if (img2 && Number(img1.data("count")) < Number(img2.data("count")))
        {
            img1.before(img2);
        }
    }
};

Fiddle. Here I'm using data attributes instead of the class attribute, which isn't designed for your case. It just swaps the elements with before() method.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105